Learn RxJS
Search…
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
1
// RxJS v6+
2
import { of } from 'rxjs';
3
import { scan } from 'rxjs/operators';
4
​
5
const source = of(1, 2, 3);
6
// basic scan example, sum over time starting with zero
7
const example = source.pipe(scan((acc, curr) => acc + curr, 0));
8
// log accumulated values
9
// output: 1,3,6
10
const subscribe = example.subscribe(val => console.log(val));
Copied!
Example 2: Accumulating an object
1
// RxJS v6+
2
import { Subject } from 'rxjs';
3
import { scan } from 'rxjs/operators';
4
​
5
const subject = new Subject();
6
//scan example building an object over time
7
const example = subject.pipe(
8
scan((acc, curr) => Object.assign({}, acc, curr), {})
9
);
10
//log accumulated values
11
const subscribe = example.subscribe(val =>
12
console.log('Accumulated object:', val)
13
);
14
//next values into subject, adding properties to object
15
// {name: 'Joe'}
16
subject.next({ name: 'Joe' });
17
// {name: 'Joe', age: 30}
18
subject.next({ age: 30 });
19
// {name: 'Joe', age: 30, favoriteLanguage: 'JavaScript'}
20
subject.next({ favoriteLanguage: 'JavaScript' });
Copied!
Example 3: Emitting random values from the accumulated array.
1
// RxJS v6+
2
import { interval } from 'rxjs';
3
import { scan, map, distinctUntilChanged } from 'rxjs/operators';
4
​
5
// Accumulate values in an array, emit random values from this array.
6
const scanObs = interval(1000)
7
.pipe(
8
scan((a, c) => [...a, c], []),
9
map(r => r[Math.floor(Math.random() * r.length)]),
10
distinctUntilChanged()
11
)
12
.subscribe(console.log);
Copied!
Example 4: Accumulating http responses over time
1
// RxJS v6+
2
import { interval, of } from 'rxjs';
3
import { scan, delay, repeat, mergeMap } from 'rxjs/operators';
4
​
5
const fakeRequest = of('response').pipe(delay(2000));
6
​
7
// output:
8
// ['response'],
9
// ['response','response'],
10
// ['response','response','response'],
11
// etc...
12
​
13
interval(1000)
14
.pipe(
15
mergeMap(_ => fakeRequest),
16
scan < string > ((all, current) => [...all, current], [])
17
)
18
.subscribe(console.log);
Copied!

Additional Resources

Last modified 1yr ago