我有一个简单的 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)