천천히 하지만 더 멀리

RxJs 를 이용한 스크롤 이벤트 스트림화 본문

front-end/React

RxJs 를 이용한 스크롤 이벤트 스트림화

PJamesY 2023. 1. 17. 17:29

많은 프론트앤드 개발자들은 스크롤 이벤트를 활용하여 개발(대표적으로 infinite scroll)을 하는 경우가 많이 있을것입니다.

한번의 스크롤로도 많은 스크롤 이벤트가 불리기 때문에 throttle 기법으로 이벤트를 처리하곤 합니다. 

throttle 기법을 rxjs 이용하여 스트림화된 이벤트를 처리하는 코드를 작성해보겠습니다.

 

throttle 이란?
이벤트가 처음 발생하고 throttle Time 으로 지정한 시간동안 발생하는 이벤트는 무시하는 기법

throttle

구현 코드

import { ReactNode, useEffect, useRef } from 'react'
import { fromEvent, throttle, interval, Subject } from 'rxjs'

const subject$ = new Subject<number>()

interface Props {
  children: ReactNode
}

export default function ScrollView({children}: Props) {
  const currentScrolledTop = useRef<number>(0)

  const handleScroll = (e: React.UIEvent<HTMLDivElement>) => {
    subject$.next(e.currentTarget.scrollTop)
  }

  useEffect(() => {
    store$.pipe(throttleTime(500)).subscribe((top: any) => {
      currentScrolledTop.current = top
    })
    numbers.subscribe(() => console.log('Next: ', currentScrolledPage.current))
  }, [])

  return (
    <section onScroll={handleScroll}>
      {children}
    </section>
  )
}

 

 

참고

https://rxjs.dev/api/operators/throttle

Comments