Ngrx polling effects stops working second time

Viewed 97
2 Answers

When you use takeWhile it completes the observable in your effect once the stop polling changes the isPollingActive to false. ngrx does not create a new effect each time you start the polling so the subsequent getDataSuccess actions effects don't happen. You can change your takeWhile to filter that way you just ignore the effects when isPollingActive is false.

I'm not sure however that this is the best approach, an action that has an effect that triggers the same action to happen again. I feel like it would be less confusing to have the start action create an interval which could fire a continue action and the stop action stop the interval.

You can move takeWhile to the inner observable (within mergeMap) pipe to resolve this issue because in this case, it will complete the inner observable, not the main effect's observable once the isPollingActive is changed:

public continuePolling$ = createEffect(() =>
  this.actions$.pipe(
    ofType(appActions.getDataSuccess),
    tap(data => console.log('app effect continue polling')),
    takeWhile(() => this.isPollingActive),
    delay(2000),
    mergeMap(() =>
      this.appDataSurvice.getData().pipe(
        switchMap(data => {
          return [appActions.getDataSuccess(data)];
        }),
        catchError(err => of(appActions.getDataFail(err))),
        takeWhile(() => this.isPollingActive), // check again incase this has been unset since delay
      )
    )
  )
);
Related