简体   繁体   中英

Rxjs wait for previous interval request execution before proceeding

Use case: call an endpoint every 3-minutes that would update a status of a certain service over the application.

my current code:

 interval(180000).subscribe(() => this.doRequest.pipe(catchError(() => { this.applicationFlag = false; return EMPTY; })).subscribe(result => this.applicationFlag = result));

My current problem is that sometimes the previous interval request has not been completed yet but the next interval request was also doing a request.

Is there a way to flag to wait for previous or don't execute the interval when the previous request is not completed yet?

When you have one subscribe inside another subscribe there's no way the outer chain can be notified that the inner chain has completed. You have to restructure your chain and use operators such as concatMap , mergeMap or switchMap . For example like the following:

interval(180000)
  .pipe(
    concatMap(() => this.doRequest.pipe(
      catchError(() => {
        this.applicationFlag = false;
        return EMPTY;
      }),
    ),
  )
  .subscribe();

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