chtefi
11/5/2016 - 5:06 PM

Rx - switchmap

Rx - switchmap

creating origin (starts at 0) with interval 500ms
creating 0nth (starts at 0) with interval 284ms
815 # 0nth (284ms): 0
creating 1nth (starts at 1000) with interval 607ms
creating 2nth (starts at 2000) with interval 971ms
creating 3nth (starts at 3000) with interval 141ms
1362 # 3nth (141ms): 3000
143 # 3nth (141ms): 3001
142 # 3nth (141ms): 3002
creating 4nth (starts at 4000) with interval 679ms
creating 5nth (starts at 5000) with interval 918ms
creating 6nth (starts at 6000) with interval 570ms
creating 7nth (starts at 7000) with interval 269ms
1847 # 7nth (269ms): 7000
creating 8nth (starts at 8000) with interval 903ms
creating 9nth (starts at 9000) with interval 970ms
creating 10nth (starts at 10000) with interval 647ms
creating 11nth (starts at 11000) with interval 319ms
2053 # 11nth (319ms): 11000
creating 12nth (starts at 12000) with interval 942ms
var Rx = require('rxjs/Rx');

const o = (name, start, interval) => Rx.Observable.create(function(observer) {
  console.log("creating " + name + " (starts at " + start + ") with interval " + interval + "ms")
  setInterval(() => observer.next({ name: name + " (" + interval + "ms)", start: start++ }), interval)
});

let start = new Date().getTime();

o("origin", 0, 500)
  .switchMap(x => o(x.start + "nth", x.start * 1000, ~~(Math.random() * 1000)))
  .subscribe(x => {
    const now = new Date().getTime()
    const delta = now - start
    console.log(delta + " # " + x.name + ": " + x.start)
    start = now
  })
// with switchMap, there is only one observable subscribed at any time. The previous is always unsubscribed from.
// it's like flatMap, with the auto-unsubscribe piece