In switch map previous subscription automatically cancelled when new subscription started. But in flatmap previous subscription not unsubscribe automatically.
Example Flatapm
const startButton = document.getElementById('start');
const startObs = Rx.Observable.fromEvent(startButton, 'click');
const intervalObs = Rx.Observable.interval(1000);
startObs
.flatMap((evt) => intervalObs)
.subscribe((x) => console.log(x));
//sample output
//0....1....2....3..0.4..1.5..2.6..
Example Swithcmap
const startButton = document.getElementById('start');
const startObs = Rx.Observable.fromEvent(startButton, 'click');
const intervalObs = Rx.Observable.interval(1000);
startObs
.switchMap((evt) => intervalObs)
.subscribe((x) => console.log(x));
//sample output
//0....1....2....3..0....1....2....3....4
https://medium.com/@kevinle/difference-between-flatmap-and-switchmap-explained-without-words-6d877cad1d60
Example Flatapm
const startButton = document.getElementById('start');
const startObs = Rx.Observable.fromEvent(startButton, 'click');
const intervalObs = Rx.Observable.interval(1000);
startObs
.flatMap((evt) => intervalObs)
.subscribe((x) => console.log(x));
//sample output
//0....1....2....3..0.4..1.5..2.6..
Example Swithcmap
const startButton = document.getElementById('start');
const startObs = Rx.Observable.fromEvent(startButton, 'click');
const intervalObs = Rx.Observable.interval(1000);
startObs
.switchMap((evt) => intervalObs)
.subscribe((x) => console.log(x));
//sample output
//0....1....2....3..0....1....2....3....4
https://medium.com/@kevinle/difference-between-flatmap-and-switchmap-explained-without-words-6d877cad1d60
No comments:
Post a Comment