From 318ce2912efbf1ab5c73dc03827c6890572d1951 Mon Sep 17 00:00:00 2001 From: Alex Kovalenko Date: Sun, 14 Feb 2021 16:29:25 +0200 Subject: [PATCH] implement when page visible custom pipe --- src/app/services/polling.service.ts | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/src/app/services/polling.service.ts b/src/app/services/polling.service.ts index 50b7af0..787bd55 100644 --- a/src/app/services/polling.service.ts +++ b/src/app/services/polling.service.ts @@ -1,7 +1,7 @@ import {Injectable} from '@angular/core'; import {HttpClient} from '@angular/common/http'; import {fromEvent, Observable, timer} from 'rxjs'; -import {concatMapTo, map, repeatWhen, shareReplay, takeUntil} from 'rxjs/operators'; +import {concatMapTo, filter, map, repeatWhen, shareReplay, takeUntil} from 'rxjs/operators'; @Injectable() export class PollingService { @@ -11,7 +11,8 @@ export class PollingService { poll(url: string, period: number): Observable { return this.http.get(url).pipe( pollWithPeriod(period), - whenOnline() + whenOnline(), + whenPageVisible(), ); } } @@ -39,3 +40,24 @@ const whenOnline = () => { ); }; }; + +const whenPageVisible = () => { + const visibilityChange$ = fromEvent(document, 'visibilitychange').pipe( + shareReplay({refCount: true, bufferSize: 1}) + ); + + const pageVisible$ = visibilityChange$.pipe( + filter(() => document.visibilityState === 'visible') + ); + + const pageHidden$ = visibilityChange$.pipe( + filter(() => document.visibilityState === 'hidden') + ); + + return (source: Observable) => { + return source.pipe( + takeUntil(pageHidden$), + repeatWhen(() => pageVisible$) + ); + }; +};