Search code examples
angulartypescriptrxjspolling

Angular conditional polling with time interval


I have a polling scenario like below where I'm polling every 1 secs to a rest API and waits for a result

interval(1000)
      .pipe(
        startWith(0),
        switchMap(() => this.itemService.getItems(shopId))
      )
      .subscribe(response => {
        console.log(response);
        
        if(response && response.status = false) {
            // stop polling
        }
        
        );
      });

polling part is working without an issue. The issue is I want the polling to stop when I get a response and its status is false. How to change this code to conditionally stop polling?


Solution

  • U can use takeWhile

     Pool()
        {
          interval(1000)
          .pipe(
            startWith(0),
            switchMap(() => this.itemService.getItems(shopId)),
            takeWhile(response=> response.status == true) //takeWhile(response=> response.status)
          )
          .subscribe(response => {
        
          });
    

    }