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

本文深入探讨了RxJS中的concatMap操作符,并将其与mergeMap和switchMap进行了对比。通过具体的示例,如使用concatMap处理点击事件并发起HTTP请求,展示了如何控制并发请求的数量,以及如何取消之前的请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值