What is MergeMap in Angular?
MergeMap essentially is a combination of mergeAll
and map. MergeAll takes care of subscribing to the 'inner' Observable so that
we no longer have to Subscribe two times as mergeAll merges the value of the
'inner' Observable into the 'outer' Observable.
The mergeMap() : Projects each source value to an
Observable which is merged in the output Observable — (Official RxJS Docs)
Why
use mergeMap?
This operator is best used when you wish to
flatten an inner observable but want to manually control the number of inner
subscriptions.
Explore in detail about Angular FAQs
Explore in detail about Angular FAQs
Example
1,
import { tap, mergeMap } from 'rxjs/operators'
sourceObservable.pipe(
tap(e => ...),
mergeMap(e => ...)
)
Example
2,
getItems(ids: number[]): Observable<Item> {
return from(ids).pipe(
mergeMap(id => <Observable<Item>> this.httpClient.get(`item/${id}`))
);
}