Search code examples
angularrxjspolling

Subscription for switchMap not called when observable takes more time


startPolling() {
timer(1, 5000).pipe(
  switchMap(() => this.gatewayService.get(this.id)),
  retry(),
  share(),
  takeUntil(this.stopPolling)
).subscribe((gateway) => {
  this.status = gateway.status;
  this.stopPollingIfImageDownloaded();
});

in the above code subscription doesnt work if gatewayService.get call takes more than 5 sec. So the switchMap cancelling the prev subscription.

Any solution to this problem.

Basically i want to do polling for status and the call may take time


Solution

  • You could either use mergeMap or exhaustMap.

    The difference is that:

    • mergeMap will subscribe every 5 seconds without unsubscribing (cancelling) the previous API call. This means you could have many concurrent subscriptions.
    • exhaustMap will not subscribe again, unless the current API call has finished, but it also will not cancel the running API call. In this case, you may need to wait up to 5 seconds after a successful response until it re-subscribes.