In Angular 1.x I would sometimes need to make multiple http
requests and do something with all the responses. I would throw all the promises in an array and call Promise.all(promises).then(function (results) {...})
.
Angular 2 best practices seem to point towards the use of RxJS's Observable
as a replacement to promises in http
requests. If I have two or more different Observables created from http requests, is their an equivalent to Promise.all()
?
forkJoin works fine too, but I'd prefer combineLatest since you don't need to worry about it taking the last value of observables. This way, you can just get updated whenever any of them emit a new value too (e.g. you fetch on an interval or something).
On reactivex.io forkJoin actually points to Zip, which did the job for me:
The more straightforward alternative for emulating
Promise.all
is to use theforkJoin
operator (it starts all observables in parallel and join their last elements):A bit out of scope, but in case it helps, on the subject of chaining promises, you can use a simple
flatMap
: Cf. RxJS Promise Composition (passing data)Update May 2019 using RxJs v6
Found the other answers useful, and wished to offer an example for the answer offered by Arnaud about
zip
usage.Here is a snippet showing the equivalence between
Promise.all
and the rxjszip
(note also, in rxjs6 how zip now gets imported using "rxjs" & not as an operator).The output from both are the same. Running the above gives: