Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

93
Views
pause interval subscription when browser tab is inactive and resume when tab is active in Angular with RXJS lib

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 
   });
   }
}
5 months ago · Santiago Trujillo
2 answers
Answer question

0

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

5 months ago · Santiago Trujillo Report

0

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);
  }
}
5 months ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.