RXJS等待所有可观测值完成并返回结果 [英] RXJS Wait for All Observables to Complete and Return Results

查看:831
本文介绍了RXJS等待所有可观测值完成并返回结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个RX流,该流将异步执行XHR调用列表,然后等待它们完成后再转到下一个调用.

I'm trying to create a RX stream that will execute a list of XHR calls async and then wait for them to complete before going to the next call.

为了帮助解释这一点,可以在普通的JS中这样写:

To help explain this could be written like this in normal JS:

try {
    await* [
        ...requests.map(r => angularHttpService.get(`/foo/bar/${r}`))
    ];
} catch(e) { throw e }

// do something

这是我正在尝试的代码,但是它是单独运行它们,而不是等它们全部完成后再继续. (这是NGRX效果流,因此与香草rx略有不同.)

This is the code I was trying but its running them individually and not waiting for them all to complete before proceeding. (This is a NGRX Effect stream so it is slightly different from vanilla rx).

mergeMap(
        () => this.requests, concatMap((resqests) => from(resqests))),
        (request) =>
            this.myAngularHttpService
                .get(`foo/bar/${request}`)
                .pipe(catchError(e => of(new HttpError(e))))
    ),
    switchMap(res => new DeleteSuccess())

推荐答案

您可以使用 forkJoin ,它将从每个已完成的观测值中发出最后一个发出的值.以下是链接文档中的示例:

You can use forkJoin, it will emit the last emitted value from each of completed observables. The following is an example from the linked documentation:

    import { mergeMap } from 'rxjs/operators';
    import { forkJoin } from 'rxjs/observable/forkJoin';
    import { of } from 'rxjs/observable/of';

    const myPromise = val =>
      new Promise(resolve =>
        setTimeout(() => resolve(`Promise Resolved: ${val}`), 5000)
      );

    const source = of([1, 2, 3, 4, 5]);
    //emit array of all 5 results
    const example = source.pipe(mergeMap(q => forkJoin(...q.map(myPromise))));
    /*
      output:
      [
       "Promise Resolved: 1",
       "Promise Resolved: 2",
       "Promise Resolved: 3",
       "Promise Resolved: 4",
       "Promise Resolved: 5"
      ]
    */
    const subscribe = example.subscribe(val => console.log(val));


彼得·B·史密斯(Peter B Smith)也有一个不错的食谱,也将forkJoin用于相同的提议:


There is also this nice recipe by Peter B Smith, also using forkJoin for the same propose:

这篇关于RXJS等待所有可观测值完成并返回结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆