[RxJS] Scan - manage the state
export class PageClickCounterComponent {
reset$ = new Subject<void>();
clicks$ = merge(
fromEvent<PointerEvent>(document, 'click').pipe(
map(accumulationHandler)
),
this.reset$.pipe(
map(resetHandler)
)
).pipe(
scan(state: PointerEvent[], stateHandlerFn) => stateHandlerFn(state), []
)
}
const accumlationHanlder = (event: PointerEvent) => (state: PointerEvent[]) => [...state, event];
const resetHandler = (event: void) => (state: PointerEvent[]) => []
The idea is attach hanlder function to each event then we just need to pass the hanlder function down to the stream instead of pass the state itself down to the steam.