Rxjs-合并2个流,并且仅在先前为true时发射

时间:2020-06-13 21:32:52

标签: rxjs

只有前一个值为true并以串行方式执行时,才可以发出信号吗?

例如(但不使用种族):

 race(this.firstObservable$, this.secondObservable$).subscribe(
      //do Something
    );

但是如果firstObservable返回false,我不希望调用secondObservable。

3 个答案:

答案 0 :(得分:0)

您可以过滤可观察对象的第一个值,如果该值为true,则switchMapTo第二个流:

this.firstObservable$.pipe(
  filter(v => v === true),
  switchMapTo(this.secondObservable$)
);

答案 1 :(得分:0)

您将需要mergeMap的某些变体来处理它。 @ eliya-cohen的答案是一个选择,替代方法是:

this.firstObservable.pipe(
  // If the source will only ever return one value then this is not necessary
  // but this will stop the first observable after the first value
  take(1), 
  // Flattens to an empty observable if the value is not truthy
  flatMap(x => iif(() => x, this.secondObservable$))
)

答案 2 :(得分:0)

基本上,您可以使用filter运算符,然后使用高阶可观察运算符switchMap(从上一个内部可观察的子项中取消),mergeMap(保留先前的内部可观察子项)之一,etc.(取决于您的需求)

this.firstObservable$.pipe(
  filter(Boolean),
  // be carefull here and instead switchMapTo use lazy alternative - switchMap
  switchMap(() => this.secondObservable$) 
);