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 )

import { Subject } from 'rxjs/Subject';
import { startWith, scan } from 'rxjs/operators';

const subject = new Subject();
//basic scan example, sum over time starting with zero
const example = subject.pipe(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 )

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

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.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/internal/patching/operator/scan.ts

results matching ""

    No results matching ""