kalamar
kalamar

Reputation: 953

$q.all() and $q.race() equivalent for Observables in Angular 2

I have two Observables as result of two different $http calls in Angular 2.

Now, I'd like to have a combined Observable that...

  1. "fires" when one of the two source Observables "fires" (race case).
  2. "fires" when both (or all) Observables "fire" (all case).

How to approach this?

Upvotes: 3

Views: 1054

Answers (1)

Andreas Jägle
Andreas Jägle

Reputation: 12260

RxJS has operators to do both of these tasks. I am referring to RxJS version 5 as you mentioned Angular 2. For RxJS version 4 the operators are named differently.

For the race task there is an RxJS operator race aligned with the Promise.race behaviour. In version 4, the operator was called amb. When switching from promises to observables, please be aware that in the observable case there could possibly be more than one item. This means that the observable that first emits an item will win and you will receive all items emitted in from this observable until it completes.

For the use case when you want to await all observables to have emitted one value, you could use the combineLatest operator. You need to pass some function on how the emitted events should be combined, which could either be returning the given array or merging the array items into one object.

Upvotes: 1

Related Questions