【问题标题】:Use takeWhile operator with different Observable source as a flag使用具有不同 Observable 源的 takeWhile 运算符作为标志
【发布时间】:2021-11-04 10:19:37
【问题描述】:

我想通过使用另一个 observable 源来取消订阅 observable。

stop$: Subject<boolean> = new Subject<boolean>();
source: Subject<string> = new Subject<string>();
this.source.pipe(takeWhile(this.stop$ === false)).subscribe()

我可以使用 takeWhile 运算符吗?

【问题讨论】:

    标签: rxjs observable reactive-programming


    【解决方案1】:

    takeWhile 运算符发出值,直到提供的表达式为 false。谓词函数应该返回 truefalse 值,所以你不能在这里使用主题(虽然你可以做一些修改并使用 BehaviourSubject 和类似但不推荐)

    已编辑:

    更好的解决方案是使用 takeUntil 运算符,如下所示:

    this.source
      .pipe(
        takeUntil(
          this.stop$.pipe(filter(val => !val))
        )
      )
      .subscribe()
    

    或者你可以提取一个 Observable:

    unsubscribe$: Observable<boolean> = this.stop$.pipe(filter(val => !val));
    
    this.source
      .pipe(takeUntil(this.unsubscribe$))
      .subscribe()
    

    【讨论】:

    • 我的问题措辞很糟糕,但这是我一直在寻找的答案。但是,我得到Property 'filter' does not exist on type 'Subject&lt;boolean&gt;'
    • 是的,当您直接从头部输入时。我将编辑我的帖子。
    猜你喜欢
    • 2022-01-01
    • 2020-01-23
    • 1970-01-01
    • 2020-02-09
    • 1970-01-01
    • 1970-01-01
    • 2010-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多