scan
signature: scan(accumulator: function, seed: any): Observable
Reduce over time.
You can create Redux-like state management with
scan!
Examples
Example 1: Sum over time
( StackBlitz )
import { of } from 'rxjs/observable/of';
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 )
import { Subject } from 'rxjs/Subject';
import { scan } from 'rxjs/operators';
const subject = new Subject();
//scan example building an object over time
const example = subject.pipe(
scan((acc, curr) => Object.assign({}, acc, curr), {})
);
//log accumulated values
const subscribe = example.subscribe(val =>
console.log('Accumulated object:', val)
);
//next values into subject, adding properties to object
// {name: 'Joe'}
subject.next({ name: 'Joe' });
// {name: 'Joe', age: 30}
subject.next({ age: 30 });
// {name: 'Joe', age: 30, favoriteLanguage: 'JavaScript'}
subject.next({ favoriteLanguage: 'JavaScript' });
Example 3: Emitting random values from the accumulated array.
( StackBlitz )
import { interval } from 'rxjs/observable/interval';
import { scan, map, distinctUntilChanged } from 'rxjs/operators';
// Accumulate values in an array, emit random values from this array.
const scanObs = interval(1000)
.pipe(
scan((a, c) => [...a, c], []),
map(r => r[Math.floor(Math.random() * r.length)]),
distinctUntilChanged()
)
.subscribe(console.log);
Related Recipes
Additional Resources
- scan
- Official docs - Aggregating streams with reduce and scan using RxJS
- Ben Lesh - Updating data with scan
- John Linquist - Transformation operator: scan
- André Staltz
Source Code:
https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/scan.ts