发现之前忘了一组处理多维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。