I'm writing an app in Angular 2 and I want to execute several http requests and run a function on the responses.
In Angular 1, I would write something like $q.all([$http.get(...), $http.get(...), ...]).then(doSomethingWithResponses);
But Angular 2 returns RxJS Observables and after a bunch of reading I still can't figure out how to get the responses of several http requests. How can this can be done?
the Promise can provide a single value, whereas the Observable is a stream of values (from 0 to multiple values), you can apply RxJS operators to the Observable to get a new tailored stream.
The Promise.all() method takes an iterable of promises as input and returns a single Promise . This returned promise fulfills when all of the input's promises fulfill (including when an empty iterable is passed), with an array of the fulfillment values.
RxJS allows to turn any Observable into a Promise with the firstValueFrom function (note: since RxJS 7, toPromise is deprecated): const obs = of(1); const promise = firstValueFrom(obs);
While an Observable can do everything a Promise can, the reverse is not true. For example, an Observable can emit multiple values over time. A Promise only resolves once.
As @Eric Martinez pointed out, there is forkJoin. forkJoin runs all observable sequences in parallel and collect their last elements.
Rx.Observable.forkJoin([a,b]).subscribe(t=> {
var firstResult = t[0];
var secondResult = t[1];
});
I'm not sure you'd want to use forkJoin/zip
, especially considering combineLatest
is easier to understand and will emit on every sub-stream event, whereas forkJoin
basically samples on every sub-stream having emitted.
This might come to bite you later when you want to combine multi-item Observables down the road.
Wouldn't a merge
work? You can subscribe and attach a handler to the onComplete
callback.
I first build an array of my observables and then use static merge
:
let obs_ary: any = [obs1, obs2, obs3];
Observable.merge(...obs_ary);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With