RxJS学习之路六(Operators(三))

发现之前忘了一组处理多维observable的操作符,现做补充。

多维observable指的是observable传出的元素同样也是observable,对这样的监听经常需要根据不同的情况对其进行不同的合并处理。

concatAll

concatAll是把传入的多个observable按顺序合并为一维,完成一个observable再进行下一个。

    interval(1000).pipe(
      map(e => interval(1000).pipe(take(4))),
      concatAll()
    ).subscribe(res => console.log(res))
    
source1 :----0----1----2----.. 
        map(e => interval(1000).pipe(take(4)))
source1 :----0----1----2----..
             \    \
             \      ----0----1----2----3--...
             ----0----1----2----3--...
             concatAll()
example: ----0----1----2----3----0---1----2----3--..
复制代码

switchAll

switchAlls是把传入的多个observable按顺序合并为一维,但是有新的observable触发,旧的就会停止。

    interval(1000).pipe(
      map(e => interval(500).pipe(take(4))),
      switchAll()
    ).subscribe(res => console.log(res))

source1 :----0----1----2----.. 
        map(e => interval(500).pipe(take(4)))
source1 :----0----1----2----..
             \    \
             \      --0--1--2--3--...
             --0--1--2--3--...
             switchAll()
example: ----0--1----0--1----0--1--..
复制代码

mergeAll

mergeAll是把传入的多个observable按顺序合并为一维,所有obserable同时按自己的事件顺序触发。

interval(1000).pipe(
      map(e => interval(500).pipe(take(15))),
      mergeAll()
    ).subscribe(res => console.log(res))
    
source1 :----0----1----2----.. 
        map(e => interval(100).pipe(take(4)))
source1 :----0----1----2----..
             \    \
             \     --0--1--2--3--...
             --0--1--2--3--...
             mergeAll()
example: ----0--1--2--03--14--025--..
复制代码

concatMap

concatAll和map结合起来的简便写法

    interval(1000).pipe(
      concatMap(e => interval(100).pipe(take(15)))
    ).subscribe(res => console.log(res))
复制代码

switchMap

switchAll和map结合起来的简便写法

interval(1000).pipe(
      switchMap(e => interval(100).pipe(take(15)))
    ).subscribe(res => console.log(res))
复制代码

mergeMap

mergeAll和map结合起来的简便写法

interval(500).pipe(
      mergeMap(e => interval(100).pipe(take(15)))
    ).subscribe(res => console.log(res))
复制代码

小结

switchMap, mergeMap, concatMap这三个操作符的共同点就是他们第一个参数的回调东西都可以直接转换为obserable,从而简化了map的生成observable的操作。三种操作符的用处各不相同:

  • 当不希望有并行处理,并且要求每个请求都能执行完全的情况适合用cancatMap;
  • 当只需要最后一次的情况时,适合用SwitchMap;
  • 当有条件进行多个并行处理,并且要求处理每个请求的情况时用mergeMap;

使用concatAll 时必要要确定observable能够结束。

操作符现在算是介绍完了,下一篇讲讲subject。

转载于:https://juejin.im/post/5ca5cce651882543f86af7af

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值