我有一个服务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();
});
});
}
我能够完成计时器,但不知道如何暂停和恢复。
最佳答案
将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();
});
关于javascript - 带暂停和恢复轮询的 Rxjs 计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53163108/