我有一项服务HomeService
,并且该服务中有此方法
getAlerts(): Observable<any> {
return this.apiService.post(`${this.DASHBOARD_URL}/alerts`);
}
因此,我有一个场景,我必须每10秒轮询一次此方法以获取新数据,并且轮询仅应在成功响应以及浏览器选项卡处于活动状态时进行。当浏览器选项卡处于非活动状态时,轮询应暂停并在选项卡处于活动状态时恢复。
我正在从组件中执行此操作:
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();
});
});
}
我能够完成计时器,但不确定如何暂停和继续。
答案 0 :(得分:0)
更改takeWhile
进行过滤
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();
});