Skip to content

Instantly share code, notes, and snippets.

@charlintosh
Created May 5, 2021 03:57
Show Gist options
  • Save charlintosh/23c0b80b689df295c13e25aec88f677b to your computer and use it in GitHub Desktop.
Save charlintosh/23c0b80b689df295c13e25aec88f677b to your computer and use it in GitHub Desktop.
import { Observable, animationFrameScheduler, fromEvent, of } from "rxjs";
import { distinctUntilChanged, filter, map, pairwise, switchMap, throttleTime } from "rxjs/operators";
import { ScrolType, ScrollMovement } from "./types";
export const watchScroll$ = (): Observable<ScrollType> =>
of(typeof window === "undefined")
.pipe(
filter((undefinedWindow) => (!undefinedWindow)),
switchMap(() => fromEvent(window, "scroll", {passive: true})),
throttleTime(0, animationFrameScheduler),
map(() => (window.pageYOffset)),
pairwise(),
map(([previous, current]) =>
(
current < previous || current === 0
? ScrollMovement.UP
: ScrollMovement.DOWN
)
),
distinctUntilChanged()
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment