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

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

多维observable指的是observable传出的元素一样也是observable,对这样的监听常常须要根据不一样的状况对其进行不一样的合并处理。ui

concatAll

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

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触发,旧的就会中止。code

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结合起来的简便写法ip

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

switchMap

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

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

mergeMap

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

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

小结

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

  • 当不但愿有并行处理,而且要求每一个请求都能执行彻底的状况适合用cancatMap;
  • 当只须要最后一次的状况时,适合用SwitchMap;
  • 当有条件进行多个并行处理,而且要求处理每一个请求的状况时用mergeMap;

使用concatAll 时必要要肯定observable可以结束。class

操做符如今算是介绍完了,下一篇讲讲subject。

相关文章
相关标签/搜索