reduce
函数签名: reduce(accumulator: function, seed: any): Observable
将源 observalbe 的值归并为单个值,当源 observable 完成时将这个值发出。
如果每次发送时都需要当前的累加值,请使用 scan!
示例
示例 1: 数字流的加和
( StackBlitz | jsBin | jsFiddle )
// RxJS v6+
import { of } from 'rxjs';
import { reduce } from 'rxjs/operators';
const source = of(1, 2, 3, 4);
const example = source.pipe(reduce((acc, val) => acc + val));
// 输出: Sum: 10'
const subscribe = example.subscribe(val => console.log('Sum:', val));
其他资源
- reduce - 官方文档
- scan() vs reduce() | RxJS 教程 - Academind
源码: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/reduce.ts