RXJS Wait for All Observables to Complete and Return Results

一世执手 提交于 2019-12-10 16:59:51

问题


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.

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

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())

回答1:


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));

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

  • Making chained API Calls using @ngrx/Effects


来源:https://stackoverflow.com/questions/48666086/rxjs-wait-for-all-observables-to-complete-and-return-results

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!