scan
연산자(operator) 정의: scan(accumulator: function, seed: any): Observable
Reduce over time.
This operator is the core for many RxJS based Redux implementations!
Examples
Example 1: Sum over time
const subject = new Rx.Subject();
//basic scan example, sum over time starting with zero
const example = subject
.startWith(0)
.scan((acc, curr) => acc + curr);
//log accumulated values
const subscribe = example.subscribe(val => console.log('Accumulated total:', val));
//next values into subject, adding to the current sum
subject.next(1); //1
subject.next(2); //3
subject.next(3); //6
Example 2: Accumulating an object
const subject = new Rx.Subject();
//scan example building an object over time
const example = subject.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
subject.next({name: 'Joe'}); // {name: 'Joe'}
subject.next({age: 30}); // {name: 'Joe', age: 30}
subject.next({favoriteLanguage: 'JavaScript'}); // {name: 'Joe', age: 30, favoriteLanguage: 'JavaScript'}
Example 3: Emitting random values from the accumulated array.
// Accumulate values in an array, emit random values from this array.
const scanObs = Rx.Observable.interval(1000)
.scan((a,c) => a.concat(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/operator/scan.ts