当多个RxJS分叉连接完成时,如何采取行动



我有两个独立的Rxjs分叉连接。我们总是运行第一个,第二个可能会有条件地运行。但当两者都完成时,或者当第一个完成时(如果没有调用第二个(,我们需要采取行动。

我怎样才能做到这一点?

sub1 = forkjoin([item1, item2])
sub2 = forkjoin([item3, item4])

您有两个要同时触发的可观察性。最简单的方法是将它们合并,并在最后与您想要采取的操作连接:

const action1$ = forkjoin([item1, item2]);
const action2$ = forkjoin([item3, item4]);
concat([
merge([action1$, action2$]),
defer(() => {
// this will happen after action1 and action2 are complete
return EMPTY;
}),
]);

您可以使用外部forkJoiniif来有条件地触发第二个可观察对象。和finalize中的管道,以便在完成时执行一些操作。

forkJoin(
forkjoin([item1, item2]),
iif(
() => someCondition,
forkjoin([item3, item4])
)
).pipe(
finalize(() => {
// do something when the source observables complete
)
)

假设第二个forkJoin是根据第一个forkJoin返回的结果触发的,我会像这个一样进行

forkjoin([item1, item2]).pipe(
// use concatMap to trigger a second Observable once the firs one has emitted
concatMap(resultOfFirst => {
// check somehow whether the condition is met
return isConditionMetToTriggerSecond(resultOfFirst) ? 
forkjoin([item1, item2]).pipe(
// use map to return both the first and the second result
map(resultOfSecond => {
return [resultOfFirst, resultOfSecond]
})
) :
// if the condition is not met return just the first result
of([resultOfFirst, null])
})
).subscribe(
// take an action when either the first or both complete
([resultOfFirst, resultOfSecond]) => {
// do something if both have been executed
if(!!resultOfSecond) {
// do stuff with both results
}
} else {  // do something if only the first has been executed
// do stuff with first result
}
)

最新更新