编程语言
首页 > 编程语言> > javascript – 为什么我的rxjs仅组合最新输出2次?

javascript – 为什么我的rxjs仅组合最新输出2次?

作者:互联网

请考虑以下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

为什么?

解决方法:

这些可观察者都没有任何延迟.一旦您订阅,source1将立即发出所有值1,2,3.然后它订阅source2,它发出的每个值与来自source1的最新值3组合.

在每个值之间添加微小延迟将强制每个事件按顺序发出. React甚至会尊重零延迟来强制执行此排序.结果是它将交替地从每个事件中取一个事件:

{
  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

标签:javascript,rxjs,rxjs5
来源: https://codeday.me/bug/20190828/1747082.html