In RxJS (Reactive Extensions for JavaScript), the
scan operator is used to perform an accumulation operation on the values emitted by an observable sequence. It resembles the
Array.prototype.reduce() function in JavaScript but operates on an observable stream of values instead of an array.
The
scan operator takes an accumulator function and an optional seed value as its parameters. The accumulator function is called for each value emitted by the source observable, and it accumulates the intermediate result based on the previous accumulated value and the current value from the source. The accumulated value is then emitted to the resulting observable sequence.
Here's the general syntax of the scan operator:
const $scanOperator = from([1,2,3,4]).pipe(
scan((sum,num) => sum+num)
);
$scanOperator.subscribe(data=> {
console.log('scan operator data', data);
});
// output :
// scan operator data 1
// scan operator data 3
// scan operator data 6
// scan operator data 10
Note: In scan operator, intermediate result is emitted while in reduce operator intermediate result is not emitted and only the final result is emitted.
Conclusion :
The scan operator is useful for scenarios where you need to maintain state or accumulate values over time, such as tracking the total count, calculating averages, or simulating a running total.