Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

map vs switchMap in RxJS

Tags:

angular

rxjs

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?

like image 963
bpoiss Avatar asked Sep 12 '19 09:09

bpoiss


People also ask

What is difference between map and SwitchMap RxJS?

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.

What is the difference between SwitchMap and map?

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.

What is the difference between map and mergeMap?

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.

What is the difference between SwitchMap concatMap and mergeMap in RxJS?

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.


2 Answers

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));
like image 196
Krishna Mohan Avatar answered Oct 19 '22 23:10

Krishna Mohan


Instead of a textual explanation, I always prefer visual explanation.

Map -

enter image description here

switchmap -

enter image description here

like image 38
Gk Mohammad Emon Avatar answered Oct 19 '22 22:10

Gk Mohammad Emon