RxJS mergeMap (flatMap) vs switchMap
mergeMap
What the doc says:
Maps each value to an Observable, then flattens all of these inner Observables using mergeAll.
mergeMap (aka flatMap) consumes all values on all streams.
let outer = Observable.interval(1000).take(2);
let source = outer.mergeMap(function (x) {
return Observable.interval(500).take(3).map(y => `stream ${x} : value ${y}`)
});
Output:
mergeMap stream 0 : value 0
mergeMap stream 0 : value 1
mergeMap stream 1 : value 0
mergeMap stream 0 : value 2
mergeMap stream 1 : value 1
mergeMap stream 1 : value 2
switchMap
What the doc says:
Maps each value to an Observable, then flattens all of these inner Observables using switch.
switchMap switches to inner observable stream when as soon as values are emitted on it.
let outer = Observable.interval(1000).take(2);
let source = outer.switchMap(function (x) {
return Observable.interval(500).take(3).map(y => `stream ${x} : value ${y}`)
});
Output:
switchMap stream 0 : value 0
switchMap stream 1 : value 0
switchMap stream 1 : value 1
switchMap stream 1 : value 2