简体   繁体   中英

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?

You can use the skipWhile rxjs operator, and like the comment suggested, set the flag to true when a pop is available, then remove it when its not:

popOpen = false;

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

see this stackblitz which shows the idea

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM