A few months back, we covered the switchMap
operator from RxJs. Today, let’s look at a similar operator called mergeMap
:
The marble diagram isn’t as obvious as it is for other operators, so let’s clarify what mergeMap
does:
- It takes values from an observable and maps them to another observable
- Then it allows us to combine the values from both observables into one new observable
What’s a real-life use case for mergeMap
?
Let’s say you want to display a list of products with their associated categories. The product information is stored in one API endpoint, and the category information is stored in another API endpoint. To display the list of products with their categories, you need to make a separate API call for each product to retrieve its category information.
You can use mergeMap
to combine the two API calls and merge the results into a single stream of data (product + category).
How is it different from switchMap
?
mergeMap
differs from switchMap
in two important ways:
switchMap
only returns the data from observable #2 –mergeMap
returns data from both observable #1 and #2 and allows us to combine that data any way we wantswitchMap
cancels observable #2 whenever observable #1 emits a new value, then re-creates another observable #2.mergeMap
doesn’t do that.
In other words, switchMap
is perfect when we want to chain asynchronous actions such as “user selects a new filter, then we request new data according to that filter” because if the user changes that filter again, we want to cancel the previous request and start a new one.