Skip to content

scan

Applies an accumulator function over the source observable and emits each intermediate result. Similar to Array.reduce but emits accumulated value after each source emission.

Timeline of observable events12345
scan((sum, x) => sum + x, 0)
Timeline of observable events1361015
// Timeline (accumulating sum):
//
// num$ 1 2 3 4 5
// sum$ 1 3 6 10 15
// | | | | |
// 0+1 1+2 3+3 6+4 10+5
//
// Explanation:
// - scan accumulates values over time using a reducer function
// - Starting with seed value 0, each emission adds to the accumulator
// - Similar to Array.reduce, but for streams
const num$ = source<number>();
const sum$ = num$.pipe(scan((acc, curr) => acc + curr, 0));
const valueHistory: number[] = [];
sum$.subscribe((x) => {
valueHistory.push(x);
});
assert.deepStrictEqual(valueHistory, [0]);
num$.next(1); // logs: 1
assert.deepStrictEqual(valueHistory, [0, 1]);
num$.next(2); // logs: 3
assert.deepStrictEqual(valueHistory, [0, 1, 3]);
num$.next(3); // logs: 6
assert.deepStrictEqual(valueHistory, [0, 1, 3, 6]);

View source on GitHub