RxJS mergeMap (2024)
RxJS Tutorial - Table of Contents
Overview
In previous article we have seen RxJS concatMap Applying Observable concatenation to a series of HTTP operations seems like a good way to ensure that the HTTP oparation happen in the intended order.
However, in some situations, we want to run things in parallel, that is why we've got the Strategy merge Observable!
So Unlike concat, Merge will not wait until the Observable finishes until the next Observable is subscribed.
Therefore, merge subscriptions to all merged observables simultaneously, and then outputs which source values that can be observed for the combined result as the multiple values are produced over time.
Merge Marble Diagram
Lets try the example of merge, as shown in the following marble diagram, to understand:
As can be seen, the merged source values for Observables appear in the output immediately. Until all the combined observables are done, the result is not Observable.
Now that we understand the merge strategy, let's see how it can be used in the higher order Observable mapping context.
RxJs mergeMap Operator
If we combine the merge technique with the notion of Observable Mapping of higher order, we get the mergeMap Operator from RxJ. Let's look at the operator's marble diagram:
This is how the operator mergeMap works:
- Every Observable source value is mapped in an Observable Internal
- The inner Observable is then subscribed by mergeMap
- When the inner observables emit new values, the output Observable will immediately reflect them
- Unlike concatMap, we do not need to wait until the previous inner observable is completed in the case of mergeMap before the next internal observable is activated
- So this means that with MergeMap (as opposed to ConcatMap), several inner observables overlap over time and emit parallel values as shown in red in the above picture.
RxJs mergeMap Operator
Here is the sample code looks like if we now use the mergeMap Operator:
this.form.valueChanges
.pipe(
mergeMap(formValue =>
this.http.put("/api/book/", formValue))
)
.subscribe(
res => ... handle successful response ...,
err => ... handle error ...
);
Now, let's assume the user communicates with the form and starts inputting data pretty quickly, and then we'd see several HTTP requests running parallel in the network log
Next we will see switchMap