[英]RxJS: How to delay next emitted value?
我有異步函數handleParamsChanges
可能需要幾秒鍾才能解決。 當 observable 發出值時,我會調用它:
this._activatedRoute.params
.subscribe(params => {
this.handleParamsChanges(params).then(() => {
// new value can be processed now
});
});
我如何修改我的代碼,以便如果 observable 一個接一個地發出 2 個值,第一個handleParamsChanges
被調用作為第一個值,並且只有在這個承諾解決后,它才會被第二個值調用,依此類推。
編輯:
這是我想出的解決方案,但我猜有更好的方法來做到這一點:
const params$ = this._activatedRoute.params;
const canExecute$ = new BehaviorSubject(true);
combineLatest(params$, canExecute$)
.pipe(
filter(([_, canExecute]) => canExecute),
map(([params]) => params),
distinctUntilChanged()
)
.subscribe(async params => {
canExecute$.next(false);
try {
await this.handleParamsChanges(params);
} catch (e) {
console.log(e);
} finally {
canExecute$.next(true);
}
})
我正在使用canExecute$
來延遲新值的處理。
我需要在這里使用distinctUntilChanged
以避免創建無限循環。
您正在尋找的是concatMap
。 在再次訂閱之前,它會等待之前的“內部 observable”完成。 你也可以大大簡化你的管道:
params$.pipe(
concatMap(params => this.handleParamsChanges(params)),
).subscribe()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.