scan
signature: scan(accumulator: function, seed: any): Observable
scan(accumulator: function, seed: any): Observable
Reduce over time.
💡 You can create Redux-like state management with scan!
Why use scan
?
scan
?The key distinction of the scan operator when compared to other reduction operators is its continuous accumulation feature. With each emitted value, the accumulator function is applied, and the accumulated result is emitted instantaneously. You can remember this by the phrase "accumulate and emit on-the-go."
The scan operator is highly useful in scenarios that require real-time monitoring and processing, such as tallying scores in a game, where you want to display the updated score each time points are added. However, be cautious when using scan for cases where the only the final accumulated result is crucial. In those situations, the reduce
operator may be more appropriate, as it emits only the final value after the source completes.
In summary, the scan operator provides a powerful and flexible means of handling continuous accumulation and emission of values, which can be especially useful in real-time monitoring and processing tasks.
Examples
Example 1: Sum over time
( StackBlitz )
Example 2: Accumulating an object
( StackBlitz | jsBin | jsFiddle )
Example 3: Emitting random values from the accumulated array.
( StackBlitz )
Example 4: Accumulating http responses over time
( StackBlitz )
Related Recipes
Additional Resources
scan 📰 - Official docs
Aggregating streams with reduce and scan using RxJS 🎥 - Ben Lesh
Updating data with scan 🎥 💵 - John Linquist
Transformation operator: scan 🎥 💵 - André Staltz
Build your own scan operator 🎥 - Kwinten Pisman
📁 Source Code: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/scan.ts
Last updated