The documentation isn't helpful enough for me to understand the difference between these.
It's like concatMap, but maps each value always to the same inner Observable. http://reactivex.io/rxjs/file/es6/operators/concatMapTo.js.html
I tried checking out learnrxjs.io's examples on stackblitz, but even with those, I wasn't able to immediately identify what the distinguishing feature was separating these.
FYI i saw this other similar question What is the difference between mergeMap and mergeMapTo? but the answer in there wasn't satisfactory, because in the learnrxjs.io examples, they clearly map to observables, not hard-coded values. https://www.learnrxjs.io/operators/transformation/concatmapto.html
If someone could provide some examples (and maybe a brief explanation) to help distinguish the *** vs the ***To higher-order observable operators, I'd appreciate that, thanks.
The RxJs mergeMap Operator as the inner Observables emit new values, they are immediately reflected in the output Observable. but unlike concatMap, in the case of mergeMap we don't have to wait for the previous inner Observable to complete before triggering the next innner Observable.
Use mergeMap if you simply want to flatten the data into one Observable, use switchMap if you need to flatten the data into one Observable but only need the latest value and use concatMap if you need to flatten the data into one Observable and the order is important to you.
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 .
💡 flatMap is an alias for mergeMap! 💡 If only one inner subscription should be active at a time, try switchMap ! 💡 If the order of emission and subscription of inner observables is important, try concatMap !
Simply said, variants with *To
will always use the same Observable that needs to be created when the whole chain is created regardless of the values emitted by the chain. They take an Observable as a parameter.
Variants without *To
can create and return any Observable only when their source Observable emits. They take a callback as a parameter.
For example when I use mergeMapTo
I'm always subscribing to the same Observable:
source.pipe(
mergeMapTo(of(1)),
)
Every emission from source
will always be mapped to of(1)
and there's no way I can change that.
One the other hand with just mergeMap
I can return any Observable I want depending on the value received:
source.pipe(
mergeMap(v => of(v * 2)),
)
Maybe an easier way to think about this is to remember that *To
variants map a value to a constant (even when it's not a "real JavaScript constant").
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