Here are two code snippets, one using map
and the other using switchMap
.
The functionality of map
is clear:
of('foo', 'bar')
.pipe(map((val) => sanitizer(val)))
.subscribe((val) => console.log('value:', val));
function sanitizer(val: string) {
return val;
}
Output:
value: foo
value: bar
However, when using switchMap
, only the last value is printed. Why does this happen?
One assumption could be that map
is for synchronous operations while switchMap
is for asynchronous operations (like returning observables or promises).
of('foo', 'bar')
.pipe(switchMap((val) => sanitizer(val)))
.subscribe((val) => console.log('value:', val));
async function sanitizer(val: string) {
return val;
}
Output:
value: bar
You can view the demonstration on StackBlitz: StackBlitz Demo