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
.
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.
combineLatest operator returns an Observable that completes when all of the observables passed in as parameters to combineLatest complete.
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).
I call combineLatest operator the independent operator. They are independent and don't wait for each other.
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.
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