一句话解释mergeMap, concatMap, switchMap, exhaustMap

11/30/2021 #rxjs #javascript

当你去窗口办事

  • mergeMap就像你有几个人办事就开几个窗口,谁先办完事就先走
  • concatMap就像只有一个窗口,谁先来先办事,后面来的要排队等前面的人办完
  • switchMap就像后来办事的会立马插队,并且赶走前面还没有办完的人
  • exhaustMap就像窗口只要有第一个人来办事,就关门,后面的都不接待。直到第一个人办完再开门。

办事=async,以上办完事=fullfilled 以下示例代码

import { from, of } from 'rxjs'
import {map,mergeMap, switchMap, concatMap, delay} from 'rxjs/operators'
const seriesOfFakeAsyncAction=(operator,name) => {
//同时发出五个async任务,随机在一秒钟之内fullfill
from([1,2,3,4,5])
.pipe(
operator(i => of(i).pipe(delay(Math.random()*1000)))
).subscribe(i => console.log(`${mergeMap} ${i} finished!`))
}
seriesOfFakeAsyncAction(mergeMap,"mergeMap")
// 结果是 1-5随机排列
seriesOfFakeAsyncAction(concatMap,"concatMap")
// 结果依次是 1,2,3,4,5
seriesOfFakeAsyncAction(switchMap,"switchMap")
// 结果只有5, 1-4被丢弃
seriesOfFakeAsyncAction(exhaustMap,"exhaustMap")
// 结果只有1, 2-5被丢弃