mergeMap / flatMap
signature: mergeMap(project: function: Observable, resultSelector: function: any, concurrent: number): Observable
mergeMap(project: function: Observable, resultSelector: function: any, concurrent: number): Observable
옵저버블과 매핑시킨 후 값을 발생시킵니다.
:bulb: flatMap과 mergeMap은 같은겁니다!
:bulb: 한번에 하나의 내부 subscription만 활성화해야하는 경우, switchMap
을 살펴보세요!
:bulb: 내부 옵저버블의 subscription과 값 발생의 순서가 중요하다면, concatMap
을 살펴보세요!
왜 mergeMap
을 사용할까요?
mergeMap
을 사용할까요?이 연산자는 내부 옵저버블은 평평하게 만들고 싶지만, 내부 subscription의 수는 조절하고싶을 때 가장 많이 쓰입니다.
예를 들어, when using switchMap
each inner subscription is completed when the source emits, allowing only one active inner subscription. In contrast, mergeMap
allows for multiple inner subscriptions to be active at a time. Because of this, one of the most common use-case for mergeMap
is requests that should not be canceled, think writes rather than reads. Note that if order must be maintained concatMap
is a better option.
Be aware that because mergeMap
maintains multiple active inner subscriptions at once it's possible to create a memory leak through long-lived inner subscriptions. A basic example would be if you were mapping to an observable with an inner timer, or a stream of dom events. In these cases, if you still wish to utilize mergeMap
you may want to take advantage of another operator to manage the completion of the inner subscription, think take
or takeUntil
. You can also limit the number of active inner subscriptions at a time with the concurrent
parameter, seen in example 5.
Examples
Example 1: mergeMap simulating save of click locations
( StackBlitz )
Example 2: mergeMap with ajax observable
( StackBlitz )
Example 3: mergeMap with promise (could also use from to convert to observable)
( StackBlitz )
Example 4: mergeMap with resultSelector
( StackBlitz )
Example 5: mergeMap with concurrent value
( StackBlitz )
Related Recipes
[Save Indicator]('../../recipes/save-indicator.md)
Additional Resources
mergeMap :newspaper: - Official
docs
:video_camera: :dollar: - Ben Lesh
Async requests and responses in RxJS
:video_camera: :dollar: - André Staltz
Use RxJS mergeMap to map and merge higher order observables
:video_camera: :dollar: - André Staltz
Use RxJS mergeMap for fine grain custom behavior
:video_camera: :dollar: - André Staltz
Build your own mergeMap operator
:video_camera: - Kwinten Pisman
:file_folder: Source Code: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/mergeMap.ts
Last updated