Question - When should we use the switchMap, mergeMap and concatMap in RxJS?
Answer -
There are mainly four types of mapping operators used in RxJS: concatMap(), mergeMap(), switchMap() and exhaustMap(). All of these operators are mapping or flattening operators used to flatten observables, but they are applicable in very different scenarios. The switchMap and mergeMap are the most powerful and frequently used operators. Let's see when we use these operators:
concatMap() Operators
Following is the sample code of concatMap() Operators:
this.form.valueChanges
.pipe(
concatMap(formValue => this.http.put("/api/book/",formValue))
)
.subscribe(
response => ... handle successful ...,
err => ... handle error ...
);
The two main benefits of using concatMap() operator are that we no longer have to use nested subscribes with higher-order mapping operator, and the second is, all http requests are sent to the backend sequentially.
This is how the concatMap operator ensures that the requests still occur in sequence:
- concatMap takes each form value and transforms it into an observer HTTP, known as an inner observer.
- concatMap subscribes to the inner Observable and sends its output to the Observable result
- The second form of value can come more quickly than is needed to request in the backend the previous form value. When this occurs, the new form value is not converted to an HTTP request immediately.
mergeMap() Operator
Unlike the RxJS concatMap operator, mergeMap() will not wait until the Observable finishes until the next Observable is subscribed.
This is how the mergeMap operator works:
- In mergeMap operator, every Observable source value is mapped in an internal Observable.
- The inner Observable is then subscribed by mergeMap.
- When the inner observables emit new values, the output Observable immediately reflects them.
- In the mergeMap, unlike the concatMap operator, we do not need to wait until the previous inner observable is completed.
switchMap() Operator
Unlike the mergeMap operator, in the switchMap operator, we unsubscribe the previous Observable before subscribing to the new Observable if the new Observable begins to emit the values.