summaryrefslogtreecommitdiffstats
path: root/src/pybind/mgr/dashboard/frontend/src/app/shared/services/timer.service.ts
blob: 716b710968f339963a4fb69ba063cb2c1a6d8dc8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import { Injectable } from '@angular/core';

import { Observable, timer } from 'rxjs';
import { observeOn, shareReplay, switchMap } from 'rxjs/operators';

import { whenPageVisible } from '../rxjs/operators/page-visibilty.operator';
import { NgZoneSchedulerService } from './ngzone-scheduler.service';

@Injectable({
  providedIn: 'root'
})
export class TimerService {
  readonly DEFAULT_REFRESH_INTERVAL = 5000;
  readonly DEFAULT_DUE_TIME = 0;
  constructor(private ngZone: NgZoneSchedulerService) {}

  get(
    next: () => Observable<any>,
    refreshInterval: number = this.DEFAULT_REFRESH_INTERVAL,
    dueTime: number = this.DEFAULT_DUE_TIME
  ): Observable<any> {
    return timer(dueTime, refreshInterval, this.ngZone.leave).pipe(
      observeOn(this.ngZone.enter),
      switchMap(next),
      shareReplay({ refCount: true, bufferSize: 1 }),
      whenPageVisible()
    );
  }
}