[英]Why my rxjs combineLatest output only 2 times?
Consider the following rxjs@5.5.11 code: 请考虑以下rxjs@5.5.11代码:
{ 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) (发出1次并持续)
value1 Latest: 3
value2 Latest: 5
or 要么
(emit 3 times and gives lasted from each) (发出3次,并从每个持续)
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) (发出2次,并从每次持续)
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
. 订阅后,
source1
将立即发出所有值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
. 然后它订阅
source2
,它发出的每个值都与source1
的最新值3
组合在一起。
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.
React甚至会尊重零延迟来强制执行此排序。 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:
原因可能是你的第一个和第二个observable发出如下内容:
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. 请注意,
combineLatest
将等到两个observable都发出值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.