Search code examples
javascriptrxjsobservablerequestanimationframe

How do would you combine Scheduler.animationFrame and fromEvent(window, 'scroll') streams in rxjs?


I have two observables Observable.of(0, animationFrame) & Observable.fromEvent(window, 'scroll'). I want to combine them so that my renderScrollBar(event) is only called on the ticks of animationFrame.

  Observable.fromEvent(window, 'scroll')
      .map((event: any) => event.currentTarget)
      .subscribe((event) => {
        this._renderScrollBar(event);
      });
  let x = 0;
  Observable.of(0, animationFrame)
      .repeat()
      .takeUntil(Observable.timer(1000))
      .subscribe(() => console.log(x++));
}

Solution

  • If you want to throttle scroll event to requestAnimationFrame you can use throttleTime(0, animationFrame) operator instead of Observable.of(0, animationFrame).

    Example

    Observable.fromEvent(window, 'scroll')
        .throttleTime(0, animationFrame)
    

    Update:

    RxJS 6

    import { fromEvent, animationFrameScheduler } from "rxjs";
    import { throttleTime } from "rxjs/operators";
    
    fromEvent(window, "scroll")
      .pipe(throttleTime(0, animationFrameScheduler))