8
votes

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.

1
This explains it beautifully. Summary: sometimes you don't need to use the returned value of an observable. Instead of map(event => 'You clicked!'), or map(() => 'You clicked!'), you can achieve the same result using mapTo('You clicked!') - Nick Bull

1 Answers

12
votes

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").