[RxJS] Use RxJS concatMap to map and concat high order observables

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 
posted @ 2016-12-19 21:49  Zhentiw  阅读(659)  评论(0编辑  收藏  举报