I read the documentation of switchMap and map, but I still don\'t completely understand the difference. Are there some cases where it does not make a difference at all?
Both operators are different.
switchMap: Maps values to observable. Cancels the previous inner observable.
Eg:
fromEvent(document, 'click')
.pipe(
// restart counter on every click
// First click: 0, 1, 2...
// Second click: cancels the previous interval and starts new one. 0, 1, 2...
switchMap(() => interval(1000))
)
.subscribe(console.log);
map: Add projection with each value.
Eg:
//add 10 to each value
const example = source.pipe(map(val => val + 10));
Are there some cases where it does not make a difference at all?
No. They are two totally different beasts. switchMap
is expected to return an observable, map
can return anything. Their application is different. It would typically go like this:
someStream$.pipe(
switchMap(args => makeApiCall(args)), // must return a stream
map(response => process(response)) // returns a value of any shape, usually an object or a primitive
).subscribe(doSomethingWithResults);
There are other operators similar in nature to switchMap
: mergeMap
(AKA flatMap
), exhaustMap
, concatMap
(and there are cases when all those amount to more or less the same thing), but not map
.
see the definitions of 2 functions:
map<inputType, outputType>(syncFunction: (input: inputType) => outputType )
switchmap<inputType, Observable<outputType>>( asyncFunction: (input: inputType) => Observable<outputType> )
map = an asynchronous function calls a synchronous function (asyncTask => syncTask)
switchMap = an asynchronous function calls an asynchronous function sequentially (asyncTask => asyncTask )
example for switchMap:
observable1 calls observable2 means:
observable1_event1 => new observable2 asynchronous => Task1
observable1_event2 => new observable2 asynchronous => Task2
observable1_event3 ...
If observable1_event2 is emitted when task1 is not completed, the Observable2 of task1 will be rejected by calling unsubscribe(). It means Task1 will not show output any more after that.
If observable1_event2 is emmitted when task1 was completed. all outputs of Task1 will be showed normally then outputs of task2 will be showed.
Note that: each new observable2 can trigger many events (observable2_event1, observable2_event2,...)
Instead of a textual explanation, I always prefer visual explanation.
Map -
switchmap -