I am working on an effect, that will be polling server.
What I want to achieve is as follows:
1) Send GET request to server
2) After response is received, wait 3 seconds
3) Send same GET request
4) After response is received, wait 3 seconds
5) Send same GET request
... and so on.
The code that I have now, doesn't quite work, as it polls server every 3 seconds, no matter if response was received or not:
@Effect()
pollEntries$ = this.actions$.pipe(
ofType(SubnetBrowserPageActions.SubnetBrowserPageActionTypes.StartPollingSubnetEntries),
switchMap(() => {
return timer(0, 3000);
}),
takeUntil(this.actions$.pipe(ofType(SubnetBrowserPageActions.SubnetBrowserPageActionTypes.StopPollingSubnetEntries))),
switchMap(() => {
return this.subnetBrowserService.getSubnetEntries();
}),
map((entries) => {
return new SubnetBrowserApiActions.LoadEntriesSucces({ entries });
}),
catchError((error) => {
return of(new SubnetBrowserApiActions.LoadEntriesFailure({ error }));
}),
);
Another thing that I am struggling with is how to stop polling. If I emit StopPollingSubnetEntries
action before request is sent to server, then it works fine - however if I emit it after request is sent, then I receive one more subsequent response, before polling stops.
I think you were close just instead of
switchMap
andtimer
you can use anddelay()
,take(1)
andrepeat()
:You could use
expand
to continuously map to the next http request and add adelay
beforehand.To start polling you have to subscribe to
pollEntries$
.Or map to the
pollEntries
whenever your action emits.https://stackblitz.com/edit/angular-mu3kp5
I wrote a blog post on this topic - https://bbonczek.github.io/jekyll/update/2018/03/01/polling-with-ngrx.html.
I've decided to create a few small effects, that when working together - will poll server. Code: