reduce:类似 JavaScript 数组中的 reduce,对数数据进行累计操作。reduce 会等待数据源中的数据流发送完成后再执行,执行时 reduce 内部遍历每一个数据流进行累计操作,操作完成得到结果将结果作为数据流发出

  1. import { interval } from "rxjs"
  2. import { take, reduce } from "rxjs/operators"
  3. interval(500)
  4. .pipe(
  5. take(5),
  6. reduce((acc, value) => acc += value, 0)
  7. )
  8. .subscribe(v => console.log())

31.png

scan:类似 reduce,进行累计操作,但执行时机不同,数据源每次发出数据流 scan 都会执行。reduce 是发送出最终计算的结果,而 scan 是发出每次计算的结果

  1. import { interval } from "rxjs"
  2. import { take, scan } from "rxjs/operators"
  3. interval(500)
  4. .pipe(
  5. take(5),
  6. scan((acc, value) => acc += value, 0)
  7. )
  8. .subscribe(v => console.log())

32.png