reduce

签名: reduce(accumulator: function, seed: any): Observable

将源 observalbe 的值归并为单个值,当源 observable 完成时将这个值发出。

:bulb: 类似于 Array.prototype.reduce()

:bulb: 如果每次发送时都需要当前的累加值,请使用 scan!

reduce - 图3

示例

示例 1: 数字流的加和

( StackBlitz |
jsBin |
jsFiddle )

  1. import { of } from 'rxjs/observable/of';
  2. import { reduce } from 'rxjs/operators';
  3. const source = of(1, 2, 3, 4);
  4. const example = source.pipe(reduce((acc, val) => acc + val));
  5. // 输出: Sum: 10'
  6. const subscribe = example.subscribe(val => console.log('Sum:', val));

其他资源


:file_folder: 源码: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/reduce.ts