使用具有不同 Observable 源的 takeWhile 运算符作为标志

Use takeWhile operator with different Observable source as a flag

我想使用另一个可观察源取消订阅一个可观察对象。

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

我可以使用 takeWhile 运算符吗?

takeWhile 运算符发出值,直到提供的表达式为假。谓词函数应该 return 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()