Like switchMap and mergeMap, concatMap is a shortcut for map() followed by a concatAll(). In this lesson we will explore this RxJS operator and its properties.
const clickObservable = Rx.Observable .fromEvent(document, 'click'); function performRequest() { return fetch('https://jsonplaceholder.typicode.com/users/1') .then(res => res.json()); } const emailObservable = clickObservable .concatMap(click => performRequest(), (click, res) => res.email); // concatMap = map ... + ... concatAll // mergeMap // switchMap emailObservable .subscribe(email => console.log(email));
concatMap happens one after the other, the same as mergeAll(1):
const emailObservable = clickObservable .mergeMap(click => performRequest(), (click, res) => res.email, 1);
So the main different between switchMap, mergeMap, concatMap are about concurrency...
- switchMap: has cancel previous request functionaility.
- mergeMap: allows num of concurrency requests
- concatMap: the same as mergeAll(1), only allow one request at a time