bluehost-banner
Retry, RetryWhen, Scan and Delay Operator - RXJS

Retry, RetryWhen, Scan and Delay Operator - RXJS

In this tutorial, we will learn about the Retry, RetryWhen, Scan, and Delay operators of RXJS.

Introduction to Retry, RetryWhen, Scan, and Delay Operator of RXJS:

Retry Operator

Retry used for re-subscriber observable in cases observable not getting subscriber first time.

Example:

fetchUsers() {
    console.log('Fetching Data...');
    this.http
      .get("https://jsonplaceholder.typicode.com/users")
      .pipe(
        retry(3) 
      )
      .subscribe(
        (res) => {
           console.log('Data Fetched');
        },
        (err) => {
          console.log('Problem Fetching Data');
         
        }
      );
  }

The above example will retry the operation three times.

Also note that The Retry operator retries the operation immediately.

If your Retry without any argument, it will retry indefinitely

retryWhen Operator

with using the RxJS retryWhen operator you can retry the request if specified conditions are met

Example:

fetchUsers() {
    console.log('Fetching Data...');
    this.http
      .get("https://jsonplaceholder.typicode.com/users")
      .pipe(
        retryWhen((err) =>
          err.pipe(
            tap(() => console.log("Retrying... "))))
          )
        )
      )
      .subscribe(
        (res) => {
          console.log('Data Fetched');
        },
        (err) => {
          console.log('Problem Fetching Data');
        }
      );
  }

Scan and Delay Operator

With using Delay operator we can delay retry attempts and with using the Scan operator we can limit retry attempts

Example:

fetchUsers() {
    console.log('Fetching Data...');
   
    this.http
      .get("https://jsonplaceholder.typicode.com/users")
      .pipe(
        //Will try for Every 3 sec
        retryWhen((err) =>
          err.pipe(
            delay(3000),
            scan((retryCount) => {
              if (retryCount >= 5) {
                throw err;
              } else {
                retryCount = retryCount + 1;
                console.log(retryCount);
                this.status = "Rerying Attempt #" + retryCount;
                return retryCount;
              }
            }, 0)
          )
        )
      )
      .subscribe(
        (res) => {
             console.log('Data Fetched');
        },
        (err) => {
          console.log('Problem Fetching Data');
        }
      );
  }

The Above example will retry operation at every 3 seconds for five time

Subscribe to our Newsletter

Stay up to date! Get all the latest posts delivered straight to your inbox.

If You Appreciate What We Do Here On TutsCoder, You Should Consider:

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never ending support.

You might also like

Leave a Comment