Skip to content

Instantly share code, notes, and snippets.

@MarsiBarsi
Created March 23, 2021 15:14
Show Gist options
  • Save MarsiBarsi/9061abc75cd12f20669e5b3fbd848f70 to your computer and use it in GitHub Desktop.
Save MarsiBarsi/9061abc75cd12f20669e5b3fbd848f70 to your computer and use it in GitHub Desktop.
the whole page visibility$ token
import {DOCUMENT} from '@angular/common';
import {inject, InjectionToken} from '@angular/core';
import {fromEvent, Observable} from 'rxjs';
import {distinctUntilChanged, map, share, startWith} from 'rxjs/operators';
export const PAGE_VISIBILITY = new InjectionToken<Observable<boolean>>(
'Shared Observable based on `document visibility changed`',
{
factory: () => {
const documentRef = inject(DOCUMENT);
return fromEvent(documentRef, 'visibilitychange').pipe(
startWith(0),
map(() => documentRef.visibilityState !== 'hidden'),
distinctUntilChanged(),
share(),
);
},
},
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment