我有一个简单的 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”方式是什么?
我希望我已经足够清楚,任何帮助都非常感谢:)
最佳答案
您还可以使用 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)
})
见 stackblitz
关于angular - RxJs - 如何使用 takeuntil 运算符返回通知程序值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61497829/