Now that mergeMap
is deprecated, and the source has this comment in it:
/* @deprecated resultSelector no longer supported, use inner map instead */
How do I use an "inner map" instead? I guess that means using the map
operator function inside of .pipe
, but the observable is not flattened, as it is with mergeMap
.
obs1$.pipe(map(() => obs2$)).subscribe(r => console.log(r === obs2$))
// > true
So, how do the equivalent of mergeMap
without it?
mergeMap is a combination of Observable merge and map . There are times when your map or projection will generate multiple Observables. For example, now I have an array of characters, and for each character, I would like to make a backend call and get some information.
The RxJs mergeMap Operatoreach value of the source Observable is still being mapped into an inner Observable, just like the case of concatMap. Like concatMap, that inner Observable is also subscribed to by mergeMap. as the inner Observables emit new values, they are immediately reflected in the output Observable.
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. For instance, when using switchMap each inner subscription is completed when the source emits, allowing only one active inner subscription.
So here's the simple difference — switchMap cancels previous HTTP requests that are still in progress, while mergeMap lets all of them finish. In my case, I needed all requests to go through, as this is a metrics service that's supposed to log all actions that the user performs on the web page, so I used mergeMap .
You still use mergeMap, it's just the resultSelector function that deprecates.
This one is not deprecated:
export function mergeMap<T, R>(project: (value: T, index: number) => ObservableInput<R>, concurrent?: number): OperatorFunction<T, R>;
However, these are:
/** @deprecated resultSelector no longer supported, use inner map instead */
export function mergeMap<T, R>(project: (value: T, index: number) => ObservableInput<R>, resultSelector: undefined, concurrent?: number): OperatorFunction<T, R>;
/** @deprecated resultSelector no longer supported, use inner map instead */
export function mergeMap<T, I, R>(project: (value: T, index: number) => ObservableInput<I>, resultSelector: (outerValue: T, innerValue: I, outerIndex: number, innerIndex: number) => R, concurrent?: number): OperatorFunction<T, R>;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With