scan

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

Reduce over time.


๐Ÿ’ก You can create Redux-like state management with scan!


Ultimate RxJS

Examples

Example 1: Sum over time

( StackBlitz )

// RxJS v6+
import { of } from 'rxjs';
import { scan } from 'rxjs/operators';

const source = of(1, 2, 3);
// basic scan example, sum over time starting with zero
const example = source.pipe(scan((acc, curr) => acc + curr, 0));
// log accumulated values
// output: 1,3,6
const subscribe = example.subscribe(val => console.log(val));

Example 2: Accumulating an object

( StackBlitz | jsBin | jsFiddle )

Example 3: Emitting random values from the accumulated array.

( StackBlitz )

Example 4: Accumulating http responses over time

( StackBlitz )

Additional Resources


๐Ÿ“ Source Code: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/scan.ts

Last updated