[英]Rxjs timer with pause and resume the poll
我有一個服務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();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.