Skip to content

Instantly share code, notes, and snippets.

@alexcastillo
Created August 17, 2020 19:02
Show Gist options
  • Save alexcastillo/5e802a40f57ce32a6d9e7864f00d96b7 to your computer and use it in GitHub Desktop.
Save alexcastillo/5e802a40f57ce32a6d9e7864f00d96b7 to your computer and use it in GitHub Desktop.
RxJS pipe: whilePageIsVisible
import { fromEvent, partition, pipe } from "rxjs";
import { shareReplay, takeUntil, repeatWhen } from "rxjs/operators";
// 🛑 unsubscribes when the browser tab is not active
// ✅ resubscribe when it is becomes active again
export function whilePageIsVisible() {
const visibilityChange$ = fromEvent(document, "visibilitychange").pipe(
shareReplay({ refCount: true, bufferSize: 1 })
);
const [pageVisible$, pageHidden$] = partition(visibilityChange$, () =>
document.visibilityState === "visible"
);
return pipe(
takeUntil(pageHidden$),
repeatWhen(() => pageVisible$)
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment