Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Promise .all() with RxJS

Tags:

angular

rxjs

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?

like image 470
benshope Avatar asked Feb 06 '16 22:02

benshope


People also ask

What is Promise in RxJS?

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.

What does Promise all do?

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.

Can we convert RxJS Observable into a Promise?

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

Do observables replace Promises?

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.


3 Answers

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];
});
like image 119
pixelbits Avatar answered Oct 12 '22 00:10

pixelbits


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.

like image 20
kakigoori Avatar answered Oct 12 '22 00:10

kakigoori


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);
like image 2
flyer88 Avatar answered Oct 12 '22 00:10

flyer88