Rxjs wait for previous interval request execution before proceeding

Viewed 375

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?

1 Answers

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();

Related