RxJS:链式可观察量不使用相同的根可观察值

时间:2017-07-25 22:43:19

标签: rxjs rxjs5

我正在努力学习RxJS,我正在尝试构建我认为简单直接的例子。创建一个在一个区间上生成的可观察的随机数,然后使用另外两个基于该可观察量的可观察量来跟踪已经看到的最低值和最高值。

rngStream似乎表现得如预期,minStream和maxStream似乎也正确跟踪。我遇到的问题是,当执行它时,似乎rngStream,minStream和maxStream在每个间隔上都有不同的随机数。我试图了解这是否是预期的,或者我是否只是错误地设置了什么。

我的目标是输出类似:

[27, 27, 27]
[13, 13, 27]
[90, 13, 90]
[42, 13, 90]
...

let rngStream = Rx.Observable
  .interval(1000)
  .map(() => Math.ceil(Math.random()*100))
  .take(5);

// Track the lowest number we've seen.
let minStream = rngStream
  .startWith(100)
  .scan((x, y) => Math.min(x, y))

// Track the highest number we've seen.
let maxStream = rngStream
  .startWith(0)
  .scan((x, y) => Math.max(x, y))

Rx.Observable.zip(rngStream, minStream, maxStream)
  .subscribe(console.log);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.4.2/Rx.min.js"></script>

1 个答案:

答案 0 :(得分:2)

https://www.youtube.com/watch?v=3LKMwkuK0ZE

这段视频实际上为我澄清了很多事情。特别是在32:00标记时,他提到了.share,这是一个可观察的多播。默认情况下,每个订阅者都会获得自己的副本所以修复看起来像这样:

let rngStream = Rx.Observable
  .interval(1000)
  .map(() => Math.ceil(Math.random()*100))
  .take(5)
  .share();

// Track the lowest number we've seen.
let minStream = rngStream
  .startWith(100)
  .scan((x, y) => Math.min(x, y))

// Track the highest number we've seen.
let maxStream = rngStream
  .startWith(0)
  .scan((x, y) => Math.max(x, y))

Rx.Observable.zip(rngStream, minStream, maxStream)
  .subscribe(console.log);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.4.2/Rx.min.js"></script>