I was reading this article and I can’t wrap my head around why switchMap
operator is preferred over other operatros like mergeMap
, concatMap
, exhaustMap
in case of short-lived, finite value, Observables
like HTTP Request?
import { of, delay, switchMap, mergeMap, concatMap, exhaustMap } from 'rxjs';
function simulateHttp(val: any, due: number) {
return of(val).pipe(delay(due));
}
const saveUser$ = simulateHttp("User saved", 1000);
const httpResult$ = saveUser$.pipe(
switchMap(sourceValue => {
console.log(sourceValue);
return simulateHttp("Data reloaded", 2000);
}
)
);
httpResult$.subscribe(
console.log,
console.error,
() => console.log('Completed httpResult$')
);