问题
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