Home > Software design >  pause interval subscription when browser tab is inactive and resume when tab is active in Angular wi
pause interval subscription when browser tab is inactive and resume when tab is active in Angular wi

Time:07-26

Having Api call each 5 min in Angular application for that used interval(10000*30).subscirbe. Now want pause the subscrition when browser tab is inactive and resume when active.

Tried below code but not working when 2 time broswer window in inactive. Api called after each 5 mins with below code and its working fine

Angular 12 and Rxjs lib is used.

 const sourceInterval = interval(1000 * 30);
   this.subscription = sourceInterval.subscribe(val => {
     
     //api call to get notification 
   });

@HostListener('document:visibilitychange', ['$event'])
visibilitychange() {
   if (document.hidden){
      this.subscription.unsubscribe();
        
   } else {
     // here i want make api call again 
     
   tired below code to make api call again but not worked as expected
    const sourceInterval = interval(1000 * 30);
   this.subscription = sourceInterval.subscribe(val => {
     
     //api call to get notification 
   });
   }
}

CodePudding user response:

No need to make it that complex, all you need is filter:

import { interval, filter } from 'rxjs';

let count = 0;

interval(1000)
  .pipe(filter(() => !document.hidden))
  .subscribe(() => console.log('API called', count  ));

Try it here: https://stackblitz.com/edit/rxjs-6mdzvf?file=index.ts

CodePudding user response:

I think @MoxxiManagarm answer could work and it's not so complex.

Personally i achieved it but without RxJs

import { Component, HostListener, OnDestroy } from "@angular/core";
import { HttpClient } from '@angular/common/http';


@Component({
  selector: 'my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.scss']
})
export class MyComponent implements OnDestroy {

  public interval: any;

  constructor(private httpClient: HttpClient) {
    this.startMakingApiCalls();
  }

  @HostListener('document:visibilitychange', ['$event'])
  public visibilitychange($event: any): void {
    if (document.hidden) {
      window.clearInterval(this.interval);
    } else {
      this.startMakingApiCalls();
    }
  }

  private startMakingApiCalls(): void {
    this.interval = window.setInterval(() => {
      console.log('MAKE API CALL');
    }, 3000);
  }

  ngOnDestroy(): void {
    window.clearInterval(this.interval);
  }
}
  • Related