Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import {Injectable} from '@angular/core';
- import {Observable, race, timer} from 'rxjs';
- import {tap, switchMap, map, retry} from 'rxjs/operators';
- import {MatDialog, MatDialogRef, ConfirmationComponent} from '../../shared';
- @Injectable()
- export class SessionExpirationService {
- private readonly EXPIRATION_TIMEOUT: number = 5000;
- private readonly REDIRECT_TIMEOUT: number = 7000;
- private dialogRef: MatDialogRef<ConfirmationComponent>;
- constructor(private dialog: MatDialog) {}
- public start(): Observable<boolean> {
- // start timer to show the confirmation
- return timer(this.EXPIRATION_TIMEOUT).pipe(
- tap(() => {
- this.dialogRef = this.dialogRef || this.createConfirmation();
- }),
- switchMap(() => {
- return race(
- // user is done if the confirmation is closed
- this.dialogRef.afterClosed().pipe(
- tap(() => this.dialogRef = null),
- map((needMoretime) => {
- // treat 'Yes' answer as an error
- if (needMoretime) {
- throw needMoretime;
- }
- return needMoretime;
- })
- ),
- // user is done after being idle for REDIRECT_TIMEOUT
- timer(this.REDIRECT_TIMEOUT).pipe(
- tap(() => {
- this.dialogRef.close();
- this.dialogRef = null;
- })
- )
- );
- }),
- // retry confirmation if user needs more time
- retry()
- );
- }
- private createConfirmation(): MatDialogRef<ConfirmationComponent> {
- return this.dialog.open(ConfirmationComponent, {
- width: '300px',
- disableClose: true,
- data: {title: 'Do you need more time?', yesText: 'Yes', noText: 'No, I\'m Done'}
- });
- }
- }
Add Comment
Please, Sign In to add comment