Sai Ram Gupta
Sai Ram Gupta

Reputation: 1181

Rxjs timer with pause and resume the poll

I have a service HomeService and has this method in the service

getAlerts(): Observable<any> {
    return this.apiService.post(`${this.DASHBOARD_URL}/alerts`);
}

so I have a scenario where I have to poll this method every 10 sec to get the new data and polling should happen only on success response and when browser tab is active. When browser tab is inactive, the polling should pause and resume when tab is active.

From the component I am doing this:

import {Subscription, timer as observableTimer} from 'rxjs';
import {delay, retryWhen, takeWhile} from 'rxjs/operators';

    private pollAlerts(): void {
             this.pollAlertsRequest = this.homeService.getAlerts().pipe(retryWhen(errors => errors.pipe(delay(10 * 1000))))
              .subscribe(res => {
                this.populateAlerts(res.alerts);
                this.alertsTimer = observableTimer(10 * 1000).pipe(
                  takeWhile(() => this.isComponentAlive))
                  .subscribe(() => {
                    this.pollAlerts();
                  });
              });
    }

I am able to get the timer done, but not sure how to pause and resume.

Upvotes: 0

Views: 1192

Answers (1)

Fan Cheung
Fan Cheung

Reputation: 11380

Change takeWhile to filter

private pollAlerts(): void {
             this.pollAlertsRequest = this.homeService.getAlerts().pipe(retryWhen(errors => errors.pipe(delay(10 * 1000))))
              .subscribe(res => {
                this.populateAlerts(res.alerts);
                this.alertsTimer = observableTimer(10 * 1000).pipe(
                  filter(() => this.isComponentAlive)),
                  switchMap(()=>interval(1000)),
                     tap(()=>this.pollAlerts());
                 ).subscribe();
              });

Upvotes: 1

Related Questions