Reduces the values from source observable to a single value that's emitted when the source completes.
💡 Just like
Array.prototype.reduce()
💡 If you need the current accumulated value on each emission, try scan!
( 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));
//output: Sum: 10'
const subscribe = example.subscribe(val => console.log('Sum:', val));
- reduce 📰 - Official docs
- Scan() vs reduce() | RxJS TUTORIAL 🎥 - Academind
- Build your own reduce operator 🎥 - Kwinten Pisman
📁 Source Code: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/reduce.ts