[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.

posted @ 2024-06-24 18:04  Zhentiw  阅读(4)  评论(0编辑  收藏  举报