首页 > 解决方案 > RxJs - 如何使用 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$)
   )

}

我想要实现的是获得通知程序发出的值作为结果。

我不需要中间值,我只需要知道它何时完成以及结果如何。


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”方式是什么?我希望我已经足够清楚了,任何帮助都非常感谢:)

标签: angulartypescriptrxjstakeuntil

解决方案


您可以merge使用原始流通知通知器并从那里获取结果,请尝试以下示例。

const notifier = timer(5000).pipe(mapTo("done"));

merge(interval(1000)
  .pipe(takeUntil(notifier)),
   notifier 
  )
  .subscribe(console.log,null,
   _=>console.log('complete') 
    );

推荐阅读