This article is based on RxJS v6 study RxJS mergeMap operator, switchMap, concatMap

mergeMap

  • Merging multiple Observables does not cancel the previous stream.

When main is subscribed, the source stream fires every three seconds. When the source stream fires, the internal stream is also fired, but after the source stream fires every three seconds, the previously incomplete stream is not interrupted.

// RxJS v6+
import { of, interval } from "rxjs";
import { mergeMap, take } from "rxjs/operators";

const source$ = interval(3000);
const main = source$
  .pipe(mergeMap((a)= > interval(500).pipe(take(10))))
  .subscribe(item= > console.log(item));
Copy the code

switchMap

  • Merging multiple Observables cancels the previous stream.

When main is subscribed, the source stream fires every three seconds. When the source stream fires, the internal stream also fires, but the source stream cancels the previous stream every three seconds.

// RxJS v6+
import { of, interval } from "rxjs";
import { switchMap, take } from "rxjs/operators";

const source$ = interval(3000);
const main = source$
  .pipe(switchMap((a)= > interval(500).pipe(take(10))))
  .subscribe(item= > console.log(item));
Copy the code

concatMap

  • Execute the next stream after waiting serialized for the previous stream to complete.
// RxJS v6+
import { of, interval } from "rxjs";
import { concatMap, mergeMap, take, delay } from "rxjs/operators";

const source$ = of(2000.1000.3000);
const concatMapExample = source$
  .pipe(concatMap(val= > of(`Delayed by:${val}ms`).pipe(delay(val))))
  .subscribe(item= > console.log(`With ConcatMap: ${item}`));

const mergeMapExample = source$
  .pipe(
    delay(8000),
    mergeMap(val= > of(`Delayed by:${val}ms`).pipe(delay(val)))
  )
  .subscribe(item= > console.log(`With MergeMap: ${item}`));
Copy the code

RxJS API List

mergeMap

switchMap

concatMap