Skip to content

Commit

Permalink
implement when page visible custom pipe
Browse files Browse the repository at this point in the history
  • Loading branch information
Alex Kovalenko committed Feb 15, 2021
1 parent fd1a143 commit 318ce29
Showing 1 changed file with 24 additions and 2 deletions.
26 changes: 24 additions & 2 deletions src/app/services/polling.service.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand All @@ -11,7 +11,8 @@ export class PollingService {
poll<T>(url: string, period: number): Observable<T> {
return this.http.get<T>(url).pipe(
pollWithPeriod(period),
whenOnline()
whenOnline(),
whenPageVisible(),
);
}
}
Expand Down Expand Up @@ -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 <T>(source: Observable<T>) => {
return source.pipe(
takeUntil(pageHidden$),
repeatWhen(() => pageVisible$)
);
};
};

0 comments on commit 318ce29

Please sign in to comment.