import { fromEvent, merge, interval, Subject, NEVER, Observable } from 'rxjs'; import { throttle, filter, switchMap } from 'rxjs/operators'; export class MwInactivityService { private inactivityInterval = 1000; private pauser = new Subject(); getCallback(inactivityTimeoutInSeconds: number): Observable { console.log('Inactivity after ' + inactivityTimeoutInSeconds); return this.pauser.pipe( switchMap((paused) => paused ? NEVER : this.source(inactivityTimeoutInSeconds) ) ); } start(): void { this.pauser.next(false); } stop(): void { this.pauser.next(true); } private source(inactivityTimeoutInSeconds: number): Observable { const mouseMove = fromEvent(document, 'mousemove'); const mouseDown = fromEvent(document, 'mousedown'); const touchMove = fromEvent(document, 'touchmove'); const touchEnd = fromEvent(document, 'touchend'); const keypress = fromEvent(document, 'keypress'); const wheel = fromEvent(document, 'wheel'); const mergedEvents = merge( wheel, mouseMove, mouseDown, touchMove, touchEnd, keypress ).pipe(throttle((t) => interval(this.inactivityInterval))); return mergedEvents.pipe( switchMap((t) => interval(1000)), filter((t) => t === inactivityTimeoutInSeconds) ); } }