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