Understanding RxJS map, mergeMap, switchMap and concatMap

Luuk Gruijs
5 min readJan 9, 2019

Mapping data is a common operation while writing your program. When you use RxJS in your code to produce your data streams it’s very likely you eventually need a way to map the data to whatever format you need it to be. RxJS comes with a ‘normal’ map function, but also has functions like mergeMap, switchMap and concatMap which all behave slightly different.

The map operator

The map operator is the most common of all. For each value that the Observable emits you can apply a function in which you can modify the data. The return value will, behind the scenes, be reemitted as an Observable again so you can keep using it in your stream. It works pretty much the same as how you would use it with Arrays. The difference is that Arrays will always be just Arrays and while mapping you get the value of the current index in the Array. With Observables the type of data can be of all sorts of types. This means that you might have to do some additional operations in side your Observable map function to get the desired result. Let’s look at some examples:

We first created our Observable with an array of cars. We then subscribe to this Observable 2 times. The first time we modify our data in such a way that we get an array of concatenated brand and model strings. The second time we modify our data so that we get an array of only Porsche cars. In both examples we use the Observable map operator to modify the data that is being emitted by the Observable. We return the result of our modification and the map operator then behind the scenes takes care of wrapping this in an Observable again so we can later subscribe to it.

MergeMap

Now let’s say there is a scenario where we have an Observable that emits an array, and for each item in the array we need to fetch data from the server.

We could do this by subscribing to the array, then setup a map that calls a function which handles the API call and then subscribe to the result. This could look like…

--

--