Is there a way to implement retry functionality with a delay in RxJs without resorting to the outdated retryWhen method?

I'd like to implement a retry mechanism for an observable chain with a delay of 2 seconds.

While researching, I found some solutions using retryWhen. However, it appears that retryWhen is deprecated and I prefer not to use it.

  • The retry with delay should only be triggered if the initial attempt fails
  • If all retries fail, I wish to handle it by providing default data

The code below works fine without the delay, but how can I incorporate a delay into this chain?

of('trigger')
  .pipe(
    switchMap(() => fetchData()),
    retry(5),
    catchError(() => of(returnThisIfRetriesAreFailed))
  )
  .subscribe(console.log);

View StackBlitz demo

I attempted to add delay(2000), but it doesn't seem to be effective.

Answer №1

It's unclear what you're asking about.

Delaying and retrying only happens if the initial attempt fails.

After reviewing the source code, I couldn't find any restrictions on using the delay option solely for the first failed try.

Therefore, you can utilize either a fixed number or an Observable as a delay. Consider this example:

of('trigger')
  .pipe(
    switchMap(() => fetchData()),
    retry({count: 5, delay: 2000}),
    catchError(() => of(returnThisIfRetriesAreFailed))
  )
  .subscribe(console.log);

If you specifically want to delay only during the first retry, you can implement something like this:

of('trigger')
  .pipe(
    switchMap(() => fetchData()),
    retry({count: 5, delay: (_, retryCount) => retryCount === 1 ? timer(2000) : of({})}),
    catchError(() => of(returnThisIfRetriesAreFailed))
  )
  .subscribe(console.log);

Answer №2

Another approach is to incorporate a method within the delay object key and perform additional validations. Here is a snippet from my code for reference.

// Custom method to determine whether to retry a request or not

shouldRetry(error: HttpErrorResponse) {
    // Example of checking for a specific error code
    if (error.status === 503) {
      return timer(1000); // Utilizing RxJS timer to create an observable for delaying
    }

    throw error;
}

// Implementing retry operator in your code base
retry({ count: 2, delay: this.shouldRetry })

Answer №3

Utilize:

of('signal').pipe(
    switchMap(() => retrieveData()),
    catchError((error, captured) => captured.pipe(
                    repeat({ times: 1, interval: 2000 }),
                    catchError(() => of(replaceWithThisIfRetryFails))
              ))
)
.subscribe(console.log);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When attempting to set a dynamic src tag for embedding a Google Map in a React application, an X-Frame-Options

I'm attempting to display a specific location using an iframe embed from Google Maps (shown below): <iframe width="100%" height="200" frameBorder="0" scrolling="no" marginHeight={0} marginWidth={0} id="g ...

Can you guide me in utilizing this API endpoint efficiently to enable search functionality using React Query?

const { isLoading, isError, data, error, refetch } = useQuery( "college", async () => { const { result } = await axios( "http://colleges.hipolabs.com/search?name=middle" ); console.log(&quo ...

I am facing an issue where my AngularJS code is not executing properly on JSF

I'm trying to clear the text inside a textarea using AngularJS after typing and clicking on a button. Here's the link to the fiddle for reference: http://jsfiddle.net/aman2690/2Ljrp54q/10/ However, I keep encountering the following error messag ...

What is the reason behind the for of loop breaking within an async function instead of properly awaiting the execution?

Update 2: I made changes to use setTimeOut instead, which fixed the issue. Check out the accepted answer for details on what was causing the error. The code below is now functioning properly. async function getSlices() { const imgBuffs = await sliceImg ...

Why does my Visual Studio Code always display "building" when I launch an extension?

https://code.visualstudio.com/api/get-started/your-first-extension I followed a tutorial to create a hello world extension. Why does my VSCode always display 'building' when I run the extension? Executing task: npm run watch < [email p ...

The client using socket.io is receiving events for "double plus one"

While experimenting with socketio, I encountered a bug that others are experiencing as well but I haven't been able to find a valid solution. This is the server-side code: const app = require('express')(); const server = require('http& ...

Tests are not visible to jasmine-node

Currently, I am utilizing jasmine-node and running it with the following command: node.exe path/to/jasmine_node --verbose path/to/my_file.js Despite successfully invoking Jasmine-node and receiving an error for incorrect paths, it appears that no tests a ...

Tips for utilizing multiple ngFor directives for property binding within a single directive

After implementing the ng-drag and drop npm module with the draggable directive, I encountered an issue while trying to display a list of items from a 2D array using li elements. Since multiple ngFor's are not allowed in Angular, I needed to come up w ...

Exploring the mechanics behind optional chaining, known as the Elvis operator, in TypeScript. How does this feature operate within the

Can someone explain the concept of optional chaining (Elvis operator) in TypeScript and how it can be used effectively? public static getName(user: IUser){ if(user.firstName != null && user.firstName != ""){ return user.firstName; } ...

How do I assign a background image to a rectangle using JointJs?

What is the best way to customize the background image of a rectangle in my JointJs project? ...

Is there a way to access a variable declared in index.js from a controller?

Currently, I am experimenting with forms-angular (). In my index.js file, I have defined a variable called DataFormHandler. However, I am facing an issue trying to access this variable in my controllers. The setter app.set("formHandler", DataFormHandler) ...

Navigating API data conversion on the frontend using Object-Oriented Programming

Currently, I am facing a challenge while developing the frontend of a web application using TypeScript. The dilemma revolves around efficiently converting a data object from an API response into a format suitable for the application. Let's consider r ...

Using Rust WebAssembly in Next.js

Seeking assistance with integrating a rust-generated wasm module into my NextJS project. This is how I am attempting to import the wasm: import init, { tokenize } from "@/wasm/lazyjson"; const Test = dynamic({ loader: async () => { ...

Establishing a custom variable within a recurring component in a form for the purpose of validation

For my booking form process, I have different sections for adults, pensioners, children, and infants. While they all share the same four inputs, each section also has some unique input fields based on the type of customer. To streamline the duplicate secti ...

"Vue component inputs fail to update when used in the same instance

I have reused the same component in both the navigation menu and on the people's page. My problem is that when the SearchComponent inputs in the navigation update their values, the SearchComponent inputs on the people's page do not update, and v ...

Having a problem with Angular 5 npm install due to a peer dependency issue

Our team is facing an issue with our Angular solution that runs smoothly on one machine, but throws errors when the 'npm install' command is executed on another machine... npm install The errors we are encountering are related to missing peer d ...

Finding items in the database using their identification numbers

I have a scenario where I am accepting a list of IDs in my request, for example [1,2,3]. How can I use typeorm and querybuilder to retrieve only objects with these IDs from my database? I attempted the following: if(dto.customersIds){ Array.prototype. ...

Generate a dot density map with the help of Google Maps

I am looking to create a dot density map using Google Maps for my state. I have all the counties outlined with their respective populations, and I want to scatter dots randomly within each county to represent the population. The goal is to make a dot densi ...

Retrieve the content text while handling errors using RxJs

When my Node.js server encounters an error with status 401, it sends out a message: https://i.stack.imgur.com/bOOF3.png https://i.stack.imgur.com/Kcv27.png The code responsible for this is as follows: res.status(401).send('Invalid user or password & ...

Assign a value to an Html.HiddenField without tying it to the model upon form submission

I have two classes, SubsidiaryClient and Client, that are related in a one-to-many manner as depicted below. Currently, I am utilizing MVC 5 for development. In the Create SubsidiaryClient page, to retrieve the ClientID, you need to click on the browse bu ...