reduce

signature: reduce(accumulator: function, seed: any): Observable

Reduces the values from source observable to a single value that’s emitted when the source completes.

:bulb: Just like
Array.prototype.reduce()

:bulb: If you need the current accumulated value on each emission, try
scan!

reduce - 图3

Examples

Example 1: Sum a stream of numbers

( 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. //output: Sum: 10'
  6. const subscribe = example.subscribe(val => console.log('Sum:', val));

Additional Resources


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