-1
 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?

Jignasha Royala
  • 1,032
  • 10
  • 27
sd_30
  • 576
  • 1
  • 6
  • 21
  • Simply add a flag type variable. If the pop up is opened then set his value to 1 and add the condition that if flag type variable is 0 then call the function otherwise no. – John Doe Feb 08 '21 at 04:54

2 Answers2

1

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

Moshezauros
  • 2,493
  • 1
  • 11
  • 15
  • Thanks I tried this, i created a global variable and changing it to false inside the dialog window and again setting to true when it closes but that not seemed to be working. – sd_30 Feb 08 '21 at 07:24
  • it shouldn't be a global variable, should be a variable in the component service which makes the http calls, if its not possible to change it from the popup, change the logic to inside the `deviceService.getDevicesList()` – Moshezauros Feb 08 '21 at 07:36
  • could you please elaborate? – sd_30 Feb 08 '21 at 07:43
  • 1
    yes, expose a function setPopupOpen(val: boolean) on `deviceService`, then the skipWhile should change to `skipWhile(() => this.deviceService.isPopupOpen)`. when you open the popup you call `this.deviceService.setPopupOpen(true)` (and with false when closing the popup), `isPopupOpen` should be a read only property exposed on `deviceService` (so only the service will change the actual private property) – Moshezauros Feb 08 '21 at 07:51
1

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

Msk Satheesh
  • 1,398
  • 1
  • 6
  • 7