javascript - 为什么可观察源在竞赛(或合并)中使用时不发出值,但在我手动订阅它时发出值

标签 javascript angular rxjs

我的代码中有三个可观察的源,它们发出相同类型的值。

    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/

相关文章:

javascript - Node.js 对象实例化是否为每个用户创建一个对象?

javascript - 如何从给定 URL 中的 JSON 数据读取 'extract' 字段

Angular *ngIf 用于嵌套表单组值

javascript - RxJs:组合两个可观察量 - 从第一个观察到的所有,但不是从第二个观察到的全部

javascript - (Angular) 拦截 HttpResponse 错误并继续 Observable

javascript - 仅当滚动条位于顶部时,模态弹出才会显示在中心

javascript - 在 Gatsby.js 中以编程方式创建多种类型的页面

javascript - {}/a/g 中的/a/g 是正则表达式还是除法?

Angular:无法解析组件的所有参数

订阅中的 Angular 订阅