switchMap
Unlike mergeMap
that will subscribe to all internal Observables created, switchMap
will discard(unsubscribe)
previous Observable once a new one is created. It is often used to cancel http request. Even if your http utility
doesn't support cancelation, switchMap
can still be used to discard stale response and use the latest one.
const fetchMovie = (name) => {
return new Prmose((resolve) => {
setTimeout(() => {
resolve({
name
})
}, 2000);
})
}
a$.pipe(
switchMap((a) => from(fetchMovie(a)))
).subscribe((b) => {
console.log(b);
})