[英]RxJs - How to return notifier value with takeuntil operator
我有一個簡單的 Rxjs 計時器,它會一直運行直到通知器發出一些東西,直到這里非常基本。
enum TimerResult = {
COMPLETE,
ABORTED,
SKIPPED
};
_notifier: Subject<TimerResult> = new Subject();
notifier$: Observable<TimerResult> = this._notifier.asObservable();
simpleTimer$ = interval(1000);
startTimer(): Observable<number> <-- **here I want a timerResult** {
return simpleTimer$.pipe(
tap(()=>doSomethingBeautifulWhileRunning),
takeUntil(this.notifier$)
)
}
我想要實現的是獲得通知程序發出的值作為結果。
我不需要中間值,我只需要知道它何時完成以及結果如何。
simpleTimer$.pipe(
tap(()=>doSomethingBeautifulWhileRunning),
last(),
takeUntil(this.notifier$)
).subscribe((result)=>{
// Here, of course, I get the last value
// I need instead the value coming from notifier$
});
我用 Rx 操作符嘗試了很多可能的解決方案,但沒有一個能按預期工作。 我發現唯一能產生可接受的結果(但恕我直言非常非常骯臟)的是:
startTimer(): Observable<TimerResult>{
simpleTimer$.pipe(...).subscribe(); <-- fire the timer, automatically unsubscribed by takeUntil
return this.notifier$.pipe(first());
}
獲得這個的最佳“Rx”方式是什么? 我希望我已經足夠清楚了,任何幫助都非常感謝:)
您可以merge
通知程序與原始 stream 合並並從那里獲取結果,請嘗試以下示例。
const notifier = timer(5000).pipe(mapTo("done"));
merge(interval(1000)
.pipe(takeUntil(notifier)),
notifier
)
.subscribe(console.log,null,
_=>console.log('complete')
);
我認為你可以merge
:
simpleTimer$.pipe(
tap(() => doSomethingBeautifulWhileRunning),
last(),
merge(this.notifier$.pipe(take(1)),
takeUntil(this.notifier$),
).subscribe((result)=>{
// Here, of course, I get the last value
// I need instead the value coming from notifier$
});
但是,我不確定它是否會按此順序工作。 也許您必須切換merge
和takeUntil
。
您也可以使用 combineLastest
startTimer(): Observable<any> {
const timer$= this.simpleTimer$.pipe(
tap((res)=>console.log(res)),
takeUntil(this.notifier$)
);
return combineLatest(timer$,this.notifier$)
}
//and use:
this.startTimer().subscribe(([timer,action])=>{
console.log(timer,action)
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.