Created
August 17, 2020 19:02
-
-
Save alexcastillo/5e802a40f57ce32a6d9e7864f00d96b7 to your computer and use it in GitHub Desktop.
RxJS pipe: whilePageIsVisible
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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