我的代码中有三个可观察的源,它们发出相同类型的值。
const setTitle$ = params$.do(
params => this.titleService.setTitle( `${params[1].appname} - ${this.pagename}` )
).switchMap(
() => Observable.of(true)
);
const openDocument$ = params$.switchMap(
params => this.openDocument(params[0].id)
);
const saveDocument$ = params$.switchMap(
params => this.saveDocument(params[0].id)
);
当我在这样的比赛中使用它们时
setTitle$.race(
openDocument$,
saveDocument$
).subscribe();
仅适用于 setTitle,当我手动订阅另外两个来源时,例如
const openDocument$ = params$.switchMap(
params => this.openDocument(params[0].id)
).subscribe();
const saveDocument$ = params$.switchMap(
params => this.saveDocument(params[0].id)
).subscribe();
然后他们也可以工作。帮助我理解为什么会发生这种情况,以及如何强制运行竞争、合并等中的所有源。
最佳答案
来自documentation ,.race()
运算符执行以下操作:
The observable to emit first is used.
这就是为什么,你只会得到一个发射,因为首先发射的三个可观察量中只有一个会被发射。
您正在寻找的是.forkJoin()
或.combineLatest()
。
如果您希望所有可观察量并行执行并等待所有观察量作为一个可观察量返回,请使用 .forkJoin()
:
Observable
.forkJoin([...setTitle$, openDocument$, saveDocument$])
.subscribe(([setTitle, openDocument, saveDocument]) => {
//do something with your your results.
//all three observables must be completed. If any of it was not completed, the other 2 observables will wait for it
})
但是,如果您想监听所有可观察量的每次发射,无论它们何时发射,请使用 .combineLatest()
:
Observable
.combineLatest(setTitle$, openDocument$, saveDocument$)
.subscribe(([setTitle, openDocument, saveDocument]) => {
//do something with your your results.
// as long as any of the observables completed, it will be emitted here.
});
关于javascript - 为什么可观察源在竞赛(或合并)中使用时不发出值,但在我手动订阅它时发出值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48255630/