Fed*_*ana 5 rxjs typescript angular takeuntil
我有一个简单的 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$)
)
}
Run Code Online (Sandbox Code Playgroud)
我想要实现的是获得通知程序发出的值作为结果。
我不需要中间值,我只需要知道它何时完成以及结果如何。
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$
});
Run Code Online (Sandbox Code Playgroud)
我使用 Rx 操作符尝试了很多可能的解决方案,但没有一个按预期工作。我发现唯一能产生可接受的结果(但恕我直言非常非常肮脏)的是:
startTimer(): Observable<TimerResult>{
simpleTimer$.pipe(...).subscribe(); <-- fire the timer, automatically unsubscribed by takeUntil
return this.notifier$.pipe(first());
}
Run Code Online (Sandbox Code Playgroud)
获得此信息的最佳“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)
})
Run Code Online (Sandbox Code Playgroud)
参见堆栈闪电战
| 归档时间: |
|
| 查看次数: |
2629 次 |
| 最近记录: |