import { Injectable, OnDestroy } from '@angular/core'; import { SettingsService } from './settings.service'; import { SelfUpdaterService } from './self-updater.service'; import { Subject, timer, Subscription } from 'rxjs'; import { ActivationStart, Router } from '@angular/router'; import { SlideShowService } from '../../display/slide-show.service'; import { filter, switchMap } from 'rxjs/operators'; const TIMER_UPDATE_POLL_INTERVAL = 30000; @Injectable() export class TimerService implements OnDestroy { private autoSwitch = false; private slideShowTimer: Subscription; private selfUpdateCheckerTimer: Subscription; private slideTimerSubject: Subject = new Subject(); private slideIntervalSubscription: Subscription; constructor(private settings: SettingsService, private selfUpdaterService: SelfUpdaterService, private router: Router, private slideShowService: SlideShowService) { const timerSUC = timer(TIMER_UPDATE_POLL_INTERVAL, TIMER_UPDATE_POLL_INTERVAL); this.selfUpdateCheckerTimer = timerSUC.subscribe(() => { this.selfUpdaterService.checkAndReloadIfNecessary(); }); this.slideShowTimer = this.slideTimerSubject .pipe(switchMap((period: number) => timer(period))) .subscribe(() => this.changeSlide()); this.setSlideTimer(this.settings.slideInterval); this.autoSwitch = false; this.router.events .pipe(filter(event => event instanceof ActivationStart)) .subscribe((event: ActivationStart) => this.autoSwitch = !!event.snapshot.data.autoSwitchable); this.slideIntervalSubscription = this.settings.slideIntervalChanged.subscribe( interval => this.setSlideTimer(interval) ); } public ngOnDestroy() { this.slideShowTimer.unsubscribe(); this.selfUpdateCheckerTimer.unsubscribe(); this.slideIntervalSubscription.unsubscribe(); } private changeSlide() { if (this.autoSwitch) { this.slideShowService.nextSlide(); } this.setSlideTimer(this.settings.slideInterval); } public setSlideTimer(delay: number) { this.slideTimerSubject.next(delay); } }