angular - RxJs - 如何使用 takeuntil 运算符返回通知程序值

标签 angular typescript rxjs

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

相关文章:

javascript - 使用 angular 4 输入文本非常慢

c# - 从 C# 类名列表中渲染打字机

javascript - 如何关闭点击外部的下拉菜单?

angular - 错误 : Please, 将您的依赖项升级到 core-js@3 的实际版本

Angular 2 输入指令修改表单控件值

typescript - NestJS 自定义装饰器返回未定义

rxjs - 可观察的发射值不会延迟

Angular 4动态创建组件并稍后检索已创建组件的列表

Angular 6 : saving data to local storage

angular - 无法绑定(bind)到 'ngClass',因为它不是 'button' 的已知属性