Search code examples
angulartypescriptrxjspolling

Detect User Activity to Keep Session Alive Strategy (RxJS)


I want to keep the user session alive with user activity defined as such.

The information system shall initiate locking of an interactive session after a 15 minute period of user inactivity (inactivity defined as no keyboard or mouse activity).

This is what i came up with.. as usual there are many ways to accomplish something in RxJS and i was wondering if there is a better way or a standard strategy

Below example will Ping the server if there is user activity every 60 seconds

const userActivityEvents = [
      fromEvent(document, 'click'),
      fromEvent(document, 'wheel'),
      fromEvent(document, 'scroll'),
      fromEvent(document, 'keypress'),
      fromEvent(document, 'mousemove'),
      fromEvent(document, 'touchmove'),
    ];

    merge(...userActivityEvents).pipe(
      throttleTime(60 * 1000),
      switchMap(() => this.apiService.get('/api/auth/ping', new HttpParams(), new HttpHeaders({ignoreLoadingBar: ''})),
      ),
    ).subscribe({error: () => undefined});


Solution

  • Since there has been no traction on this i might as well leave my final answer.

          this.ngZone.runOutsideAngular(() => {
            merge(
              fromEvent(document, 'click'),
              fromEvent(document, 'wheel'),
              fromEvent(document, 'scroll'),
              fromEvent(document, 'keypress'),
              fromEvent(document, 'mousemove'),
              fromEvent(document, 'touchmove'),
            ).pipe(
              throttleTime(USER_ACTIVITY_POLL_TIME),
              skip(1),
              filter(() => !this.sessionModal),
              filter(() => this.authService.authenticated),
              switchMap(() => this.authService.ping(new HttpHeaders({ignoreLoadingBar: ''}))),
            ).subscribe({error: () => undefined});
          });