Search code examples
javascriptangulartypescriptangular-materialpolling

How do i stop polling when user opens a popup?


 update(){
    this.timeInterval = interval(2000).pipe(startWith(0), switchMap(() => this.deviceService.getDeviceList())
    ).subscribe((success: any) => {
      this.rowData = success;
      console.log("hello")
    },
    retry(2)
    );
  }

I have this code which fetches the details after every 2sec. but i want to pause this method whenever user opens up any popup and again start it once he closes the pop. Not getting how can i achieve this in angular?


Solution

  • User takeUntill and repeatWhen for acheive this. If you call the flag$ with the this.flag$.next(false) it will stop. To resume you need to call with this.flag$.next(true). check the stackblitz for more clearence.

    flag$: Subject<boolean> = new Subject<boolean>();
    
    this.timeInterval = interval(2000)
          .pipe(
            startWith(0),
            switchMap(() => this.getUsers())
          )
          .pipe(
            takeUntil(this.flag$),
            repeatWhen(() => this.flag$)
          )
          .subscribe((success: any) => {
            console.log(success);
          }, retry(2));
    

    Here the stackblitz example: https://stackblitz.com/edit/angular-ivy-cisbks?file=src/app/app.component.ts