1
votes

I'm studing RxJS; I don't understand why mergeMap and switchMap give me the same result; the following source code comes from https://codeburst.io/rxjs-by-example-part-2-8c6eda15bd7f with my little modification (use of new Observable and myObservable part):

import { of, Observable, Observer } from 'rxjs';
import { map, mergeAll, delay, switchAll, switchMap, mergeMap, bufferCount, filter } from 'rxjs/operators';

const myObservable = new Observable((observer) => {
  observer.next(1);
  observer.next(2);
  observer.next(3);
  observer.next(4);
});
const multiplyObservable = myObservable.pipe(map((o: any) => o * 2));
const filterObservable = myObservable.pipe(filter((o: any) => o < 3));
console.log('MY_OBSERVABLE');
myObservable.subscribe(o => console.log(o));
console.log('MULTIPLY_OBSERVABLE');5
multiplyObservable.subscribe(o => console.log(o));
console.log('FILTER_OBSERVABLE');
filterObservable.subscribe(o => console.log(o));

const myAllObservable=myObservable.pipe(
    map((o: any) => o * 2),
    filter((o: any) => o < 5),
    switchMap((o: any)=> of(o+10))
    // mergeMap((o: any)=> of(o+10))
);

console.log('ALL_OBSERVABLE');
myAllObservable.subscribe(o => console.log(`myAllObservable: ${o}.`));

If I comment switchMap and execute mergeMap, the result is the same? Why?

1
This article might help explain it for you.Andrew Nolan

1 Answers

1
votes

What you see is happening because of() emits always synchronously (unless you pass it a scheduler which is deprecated). Also, of() emits all its values immediately on every subscription. So it doesn't matter if you use mergeMap or switchMap because when switchMap unsubscribes on a new emission from its source then of() has already emitted everything.

Try adding of(o+10).pipe(delay(0)) and I think you will see a difference because even with 0 delay this will force async emission and switchMap will have time to unsubscribe.