Consider the following rxjs@5.5.11 code:
{ const source1 = Rx.Observable.of(1, 2, 3); const source2 = Rx.Observable.of(4, 5); const combined = Rx.Observable.combineLatest(source1, source2); const subscribe = combined.subscribe(([value1, value2]) => { console.log(`value1 Latest: ${value1}`); console.log(`value2 Latest: ${value2}`); }); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.11/Rx.min.js"></script>
I imagined this result would be something like this:
(emit 1 time and gives lasted)
value1 Latest: 3
value2 Latest: 5
or
(emit 3 times and gives lasted from each)
value1 Latest: 1
value2 Latest: 4
value1 Latest: 2
value2 Latest: 5
value1 Latest: 3
value2 Latest: 5
but actually it is:
(emit 2 times and gives lasted from each)
value1 Latest: 3
value2 Latest: 4
value1 Latest: 3
value2 Latest: 5
Why?
Neither of these observables have any delay. As soon as you subscribe, source1
will instantly emit all of the values 1, 2, 3
. And then it subscribes to source2
and each of the values that it emits are combined with the latest value, 3
, from source1
.
Adding a tiny delay between each value will force each event to be emitted in sequence. React will even respect a zero delay to enforce this ordering. The result is that it will alternately take one event from each:
{
const source1 = Rx.Observable.of(1, 2, 3)
.zip(Rx.Observable.timer(0, 0), (x, _) => x);
const source2 = Rx.Observable.of(4, 5)
.zip(Rx.Observable.timer(0, 0), (x, _) => x);
const combined = Rx.Observable.combineLatest(source1, source2);
const subscribe = combined.subscribe(([value1, value2]) => {
console.log(`value1 Latest: ${value1}`);
console.log(`value2 Latest: ${value2}`);
});
}
value1 Latest: 1
value2 Latest: 4
value1 Latest: 2
value2 Latest: 4
value1 Latest: 2
value2 Latest: 5
value1 Latest: 3
value2 Latest: 5
Visual explanation may be good here. The reason may be your first and second observables emitted something like the following:
First observable: -----1------2------3
Second observable: -----------------------4-----5
Result: ---------------------[3,4]--[3,5]
Please note that the combineLatest
will wait till both observables emit values.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.