有没有办法只在以前的值为真时才发出并以串行方式发出?
例如(但不使用种族(:
race(this.firstObservable$, this.secondObservable$).subscribe(
//do Something
);
但是我不希望如果 firstObservable 返回 false,则调用 secondObservable。
可以过滤可观察量的第一个值,如果值true
,则 switchMap 到第二个流:
this.firstObservable$.pipe(
filter(v => v === true),
switchMapTo(this.secondObservable$)
);
您需要一些mergeMap
变体来处理它。 @eliya-科恩的答案是一种选择,另一种选择是:
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$))
)
基本上你可以使用filter
运算符,然后使用高阶可观察运算符之一switchMap
(来自前一个内部可观察量的 unsub(、mergeMap
(保留以前的内部可观察子(等(取决于你的需要(
this.firstObservable$.pipe(
filter(Boolean),
// be carefull here and instead switchMapTo use lazy alternative - switchMap
switchMap(() => this.secondObservable$)
);