如何在下一次只发射一个观测者的情况下连接观测者



你好,我想用rxjs实现一些有一些约束的东西,但我不能同时实现所有约束。

我想要实现的目标可能是这样的:

first$      ---x|
second$         ------x|
subscribe   -----------x|

但这就是我得到的:

first$      ---x|
second$         ------x|
subscribe   ---x------x

使用此代码:

const checkFirstSide$: Observable<boolean> = this.checkSide('first');
const checkOtherSide$: Observable<boolean> = this.checkSide('other');
concat(
checkFirstSide$,
checkOtherSide$
).pipe(
timeout(15000)
).subscribe({
next: (success) => {
doSomething(success);
},
error: (error) => {
handleError(error);
},
complete: () => {
doSomethingOnComplete();
}
});

限制条件:

  1. 他们应该一个接一个地订阅
  2. 只有在前一个成功(不发出错误(的情况下,他们才应该订阅
  3. 一切都应该在15秒内超时
  4. 出现任何错误时,它都应该中止(执行handleError并完成(
  5. 观察器next功能应只执行一次,然后执行complete

要么。。。

当第一发射时切换到第二可观测。

checkFirstSide$.pipe(
switchMap(x => checkOtherSide$),
timeout(15000)
)

或者从你的可观测值中收集值,并在最后发出它们。

concat(
checkFirstSide$,
checkOtherSide$
).pipe(
toArray(),
timeout(15000)
)

我相信您想要的行为是通过forkJoin函数实现的。查看API官方参考资料!

编辑:对不起,我误解了你的想法!我想我现在明白了。。。您需要的是使用管道和switchMap操作符:
checkFirstSide$.pipe(
switchMap(resFirstSide => {
doSomething(resFirstSide);
return checkOtherSide$;
});
).subscribe(resOtherSide => doSomethingOnComplete());

我认为最接近API官方参考的是concat。但我不确定当一个可观察到的投掷时,它会如何表现。

最新更新