RxJS Operator: mergeMap
Deborah Kurata
Posted on August 19, 2021
The mergeMap
RxJS Operator is a higher-order mapping operator that processes each emitted value as it is emitted and returns the results as soon as they are available, which may not be in the order of the requests.
For example:
products$ = this.categorySelected$
.pipe(
mergeMap(catId=>
this.http.get<Product[]>(`${this.url}?cat=${catId}`))
);
In the above code, the mergeMap
will perform the HTTP get as soon as an Id is emitted from this.categorySelected$
. When another Id is emitted, that request is performed concurrently.
How Does mergeMap Work?
We can think of the mergeMap like the 800 m race: the runners all start at the same time. And they will finish the race as quickly as they can. The order of the finish won't necessarily be the order they started.
Let's look at an Example
In this example, the user clicks the category with an id of 2, changes their mind and picks 3, then decides they really want category 1.
Following the numbers on the screen shot above:
- The mergeMap issues a get request for category 2,
- when emitted, it issues a get request for category 3,
- when emitted, it then issues a get request for category 1.
- The result is emitted as soon as the response is returned.
- In the above example, the response for category 3 returns first,
- the response for category 1 returns next,
- and lastly the response for category 2 returns.
For this specific example, where the user can change their mind on the selected category, using mergeMap doesn't make sense. As shown in the above example, the last returned result may not be related to the most recent selection. (The user picked 1 last, but they now see the result for category 2.)
When Should We Use mergeMap?
The mergeMap is great for related data. Say we had a set of customer Ids and we wanted to get the detail for all of them, in no particular order. Using a mergeMap will get the data for all of them concurrently, providing a more performant user experience than getting them sequentially, one at a time, as with concatMap.
Posted on August 19, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.