Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the order of observables given to combineLatest relevant?

Tags:

rxjs

reactive

I have two observables which I want to combine with combineLatest:

const o1 = from(['a', 'b', 'c']);
const o2 = of('content from o2');
combineLatest(o1, o2)
  .subscribe(result => console.log(result));

As I understood combineLatest, when any observable emits, it will combine the latest values of all observables and emit them:

When any observable emits a value, emit the latest value from each. (https://www.learnrxjs.io/operators/combination/combinelatest.html)

However, with the code above, the output is:

["c", "content from o2"]

So only when o2 emits, combineLatest emits an value.

If I switch the order I hand over o1 and o2, it works as expected:

const o1 = from(['a', 'b', 'c']);
const o2 = of('content from o2');
combineLatest(o2, o1)
  .subscribe(result => console.log(result));

Output:

["content from o2", "a"]
["content from o2", "b"]
["content from o2", "c"]

Is this expected behavior? If so, why? This seems to contradict the definition ob combineLatest.

like image 593
fjc Avatar asked Aug 03 '18 16:08

fjc


People also ask

What is observable combineLatest?

When any of the source Observables emits an item, CombineLatest combines the most recently emitted items from each of the other source Observables, using a function you provide, and emits the return value from that function.

Does combineLatest complete?

combineLatest operator returns an Observable that completes when all of the observables passed in as parameters to combineLatest complete.

What is the use of combineLatest in angular?

combineLatest allows to merge several streams by taking the most recent value from each input observable and emitting those values to the observer as a combined output (usually as an array).

Does combineLatest wait?

I call combineLatest operator the independent operator. They are independent and don't wait for each other.


1 Answers

Yes, in this case order matters, but it is a timing issue. combineLatest can not influence the order in which the values of the observables are emitted.

In your first case, o1 emits all values before o2 emits its value. In your second case o2 emits its value first and then o1 emits all its values. In real world examples you have a natural delay of observable values (service calls etc..) and so normally order does not matter.

like image 191
René Winkler Avatar answered Nov 07 '22 05:11

René Winkler