I read the documentation of switchMap and map, but I still don't completely understand the difference. Are there some cases where it does not make a difference at all?
map(function(value) { return value*10; }). subscribe(observer); SwitchMap - switchMap will subscribe to all the inner Observables inside the outer Observable but it does not merge the inner Observables. It instead switches to the latest Observable and passes that along to the chain.
Map is 1 to 1 mapping which is easy to understand. SwitchMap on the other hand only mapping the most recent value at a time to reduce unnecessary compute.
mergeMap is a combination of Observable merge and map . There are times when your map or projection will generate multiple Observables. For example, now I have an array of characters, and for each character, I would like to make a backend call and get some information.
Use mergeMap if you simply want to flatten the data into one Observable, use switchMap if you need to flatten the data into one Observable but only need the latest value and use concatMap if you need to flatten the data into one Observable and the order is important to you.
Both operators are different.
switchMap: Maps values to observable. Cancels the previous inner observable.
Eg:
fromEvent(document, 'click')
.pipe(
// restart counter on every click
// First click: 0, 1, 2...
// Second click: cancels the previous interval and starts new one. 0, 1, 2...
switchMap(() => interval(1000))
)
.subscribe(console.log);
map: Add projection with each value.
Eg:
//add 10 to each value
const example = source.pipe(map(val => val + 10));
Instead of a textual explanation, I always prefer visual explanation.
Map -
switchmap -
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With