Skip to content

Instantly share code, notes, and snippets.

@AndrWeisR
Last active September 4, 2020 01:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndrWeisR/c195c60e75b53a3957d5ea5b0ee9ea1f to your computer and use it in GitHub Desktop.
Save AndrWeisR/c195c60e75b53a3957d5ea5b0ee9ea1f to your computer and use it in GitHub Desktop.
RxJs merge example - mergeMap, concatMap, switchMap
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<div id="app">
<button id="a">Start A Sequence</button>
</div>
<script src="src/index.ts"></script>
</body>
</html>
import { fromEvent, interval } from "rxjs";
import { map, mergeMap, take, concatMap, switchMap } from "rxjs/operators";
const getElem = (id: string): HTMLElement => document.getElementById(id);
const fromClick$ = (id: string) => fromEvent(getElem(id), "click");
const streamA = interval(500).pipe(
take(10),
map((val) => "A" + val)
);
// When the button is clicked, start emitting a sequence of 10 values, A0,A1,A2 etc.
// mergeMap will merge multiple streams, so you get interleaved "A" values every time you click.
// concatMap will only start emitting values after the previous sequence has completed.
// switchMap will start emitting a new sequence after each click.
const a$ = fromClick$("a").pipe(
// mergeMap((_) => streamA)
concatMap((_) => streamA)
// switchMap((_) => streamA)
);
a$.subscribe(console.log);

Example that demonstrates the differences between mergeMap, concatMap and switchMap. Click the button to create an observable that emits 10 values in sequence, A0,A1,A2 etc.

  • mergeMap will merge multiple streams, so you get interleaved "A" values every time you click.
  • concatMap will only start emitting values after the previous sequence has completed.
  • switchMap will start emitting a new sequence after each click.

Code sandbox: https://codesandbox.io/s/rxjs-merge-examples-4wffj?file=/index.html:0-236

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment