Demo:  switchMapTo

switchMapTo is the same as switchMap as long as the mapped observable is independent of the incoming values.

The above relation comes from the relation between map and mapTo

const source=timer(500,2500).pipe(take(3));

//1. Each input from source maps to this counting task
const countTill3Task = timer(0,1700).pipe(take(4));

//2. switchMapTo keeps switching to the latest countTill3Task,
// cancelling any unfinished older task.
const mapToAndSwitchToLatest = switchMapTo( countTill3Task );

const output = source.pipe(mapToAndSwitchToLatest).subscribe(v=>console.log(v))
What is happening ?

The switchMapTo is the same as switchMap:

  • With the differnce being on their mapping part.
  • switchMapTo usages the mapTo instead of the map operator for creating the desired task.
  • As a result, using switchMapTo we can only map to a task which is independent of the incoming value.

Except this difference in the mapping, both are the same on the task execution part:

  • Both switch to the latest task on hand, cancelling any earlier in-complete task. As a result, we can see that the outcome of the demo for both are the same:
  • Here switchMapTo started the countTill3Task for 1 as it arrived, cancelling the on-going count task for 0.
  • Again, started the countTill3Task for 2 as it arrived, cancelling the on-going count task for 1. .