DEV Community

subrata71
subrata71

Posted on

How to Run an Asynchronous Task in Spring WebFlux Without Blocking the Main Response?

I'm working with Spring WebFlux and I need to perform an asynchronous task as part of a method that should not block the main response to the user. Specifically, I want to call an asynchronous method after completing the main task, but without delaying the response.

Here's a simplified version of what I'm trying to achieve:

public Mono<ResponseDTO> publishPackage(RequestDTO requestDTO) {
    return publishPackageService.doSomething(requestDTO)
        .flatMap(responseDTO -> 
            doSomethingInAsync(requestDTO, responseDTO)
                .thenReturn(responseDTO)
        );
}

// Method that simulates an asynchronous task with a 5-second delay
public Mono<Void> doSomethingInAsync(RequestDTO requestDTO, ResponseDTO responseDTO) {
    return Mono.delay(Duration.ofSeconds(5))
        .then(); // Converts the delayed Mono<Long> to Mono<Void>
}

Enter fullscreen mode Exit fullscreen mode

After this call completes, I want to execute doSomethingInAsync(requestDTO, responseDTO) asynchronously.
The doSomethingInAsync method should be non-blocking and not delay the main response.
Problem:

The doSomethingInAsync method is being executed, but it seems like it might be blocking the response or not running asynchronously as intended. How can I ensure that doSomethingInAsync runs asynchronously and does not block the response to the user?

Details:

publishPackageService.doSomething(requestDTO): Returns a Mono.
doSomethingInAsync(requestDTO, responseDTO): Is an asynchronous method that I want to run without blocking the response.

Questions:

How can I ensure doSomethingInAsync runs in the background without blocking the response?

Top comments (0)