scan

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

Reduce over time.


:bulb: This operator is the core for many RxJS based Redux implementations!


Examples

Example 1: Sum over time

( jsBin | jsFiddle )

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

( jsBin | jsFiddle )

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.

( jsBin | jsFiddle )

// 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);

Additional Resources


:file_folder: Source Code: https://github.com/ReactiveX/rxjs/blob/master/src/operator/scan.ts

results matching ""

    No results matching ""