考虑以下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>
我想象这个结果会是这样的:
(发射1次并持续)
value1 Latest: 3
value2 Latest: 5
或
(发射3次并从每次发射持续)
value1 Latest: 1
value2 Latest: 4
value1 Latest: 2
value2 Latest: 5
value1 Latest: 3
value2 Latest: 5
但实际上是:
(发射2次并从每次发射中持续)
value1 Latest: 3
value2 Latest: 4
value1 Latest: 3
value2 Latest: 5
为什么?
答案 0 :(得分:3)
这些观察者都没有任何延迟。订阅后,string str1 = Transform("<+<+>><+<+><>><+><+<<>>>");
string str2 = Transform("<aaa+aaa<aaa+aaa><aaa+aaa>><aaa+aaa>");
会立即发出所有值source1
。然后它订阅1, 2, 3
,并将其发出的每个值与source2
中的最新值3
合并。
在每个值之间添加一个微小的延迟将强制按顺序发出每个事件。 React甚至会尊重零延迟来强制执行此排序。结果是它将交替地从每个事件中取一个事件:
source1
{
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}`);
});
}
答案 1 :(得分:2)
视觉解释在这里可能会很好。原因可能是您的第一个和第二个可观察者发出如下内容:
First observable: -----1------2------3
Second observable: -----------------------4-----5
Result: ---------------------[3,4]--[3,5]
请注意,combineLatest
将等到两个观察者都发出值。