rxjs5 - RxJS: Chained Observables Not Using the Same Root Observable Values -
i'm trying learn rxjs , attempting build thought simple , straightforward example. create observable of random numbers generated on interval, use 2 other observables based on observable track lowest , highest values had been seen.
the rngstream seems behave expected, minstream , maxstream both appear track correctly well. problem i'm having when executes seems rngstream, minstream, , maxstream have different random numbers on each interval. i'm trying understand if that's expected or if i've set incorrectly.
my goal output like:
[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 lowest number we've seen. let minstream = rngstream .startwith(100) .scan((x, y) => math.min(x, y)) // track 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>
https://www.youtube.com/watch?v=3lkmwkuk0ze
this video clarified lot of things me. @ 32:00 mark mentions .share
makes observable multicast. default every subscriber own copy. fix looks this:
let rngstream = rx.observable .interval(1000) .map(() => math.ceil(math.random()*100)) .take(5) .share(); // track lowest number we've seen. let minstream = rngstream .startwith(100) .scan((x, y) => math.min(x, y)) // track 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>
Comments
Post a Comment