Hey I am new to rxjs and ngrx, and I am building an app using these technologies. I am trying to think on how to create a Polling system using rxjs observables and operators.
I have created a basic Polling system which contains a map of subscriptions of the observables. each observable dispatch an action every 5 seconds to ngrx-effects which handle the action and perform the side effects like http call using a service.
My problem is that I want to create a specific mechanisim for current pooling system which has the following conditions:
1.The first pool happens right away,I am using timer(0,poolingTime) for this, or interval with pipe of stratwith(null).
2.The pool know to delay its next request according to the time of the previous request.I mean that when the previous request finished then the second request occur.
The first conidition I have acheived alone , the second condition(2) I need help in achieving this. I thoungth about debounce or throttle inorder to complete the second condition, but as I said in the first place I don't have alot of expriences with rxjs.
Here is the code of my simple pooling system
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';
import { timer } from 'rxjs/observable/timer';
import { interval } from 'rxjs/observable/interval';
import { throttleTime, debounceTime, startWith, tap, delay } from 'rxjs/operators';
import { Utils } from '../utils';
@Injectable()
export class PoolingService {
private subscriptions: { [id: string]: Subscription };
constructor() {
this.subscriptions = {};
}
public startPooling(time: number, callback: Function): string {
const id = Utils.guid();
const interval$ = interval(time).pipe(tap(tick => console.log("tick", tick))).pipe(startWith(null));
// const interval$ = timer(0, time).pipe(tap(tick => console.log("tick", tick)));
const subscription = interval$.subscribe(() => { callback() });
this.subscriptions[id] = subscription;
return id;
}
public stopPooling(id: string) {
const subscription = this.subscriptions[id];
if (!subscription) {
return;
}
subscription.unsubscribe();
}
}
Here is the use of the Poll Service:
ngOnInit() {
this.store.select('domains').subscribe((state: any) => {
const { list, lastAddedDomain } = state;
this.markers = list;
this.roots = Utils.list_to_tree(list);
});
this.poolService.startPooling(5000, () => {
this.store.dispatch(new AllHttpActions.HttpActionGet({}, HttpMethods.GET, "/getDomainsForMap", AllDomainActions.FETCH_DOMAINS, Utils.guid()));
});
}