'Reactor Mono, how to synch process (using .map()) and return Mono<void> from response.setComplete()

I have this method which gets redirection url and then redirect to that url

private Mono<Void> redirectToUrl(ServerHttpResponse response, String status) {
        String queryParameter = "?status=" + status;
        return getRedirectUrl(queryParameter)
                .flatMap(url -> {
                    response.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
                    response.getHeaders().setLocation(url);
                    return response.setComplete();
                });
    }

in the 4th line i am using flatmap which will modify the response object asynch, in that case the response will be returned to the client immediately without the redirection.

I cannot use map() with response.setComplete() because it will return Mono<Mono<void>>, i need to return Mono<void>

How can i process synchronously

 response.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
                    response.getHeaders().setLocation(url);
                    return response.setComplete();

and return Mono<void>



Solution 1:[1]

If you must process it synchronously, you could use map(), then call .then(), which will wait for the Mono to complete then simply relay the completion signal.

However, from my understanding the flatMap() call should work ok as-is, because the Mono still won't complete until that flatMap() completes - that should make no difference if it's asynchronous or not. I suspect the actual reason why your code isn't functioning as intended is because whatever method is calling redirectToUrl() isn't waiting for the returned Mono to complete before returning the response.

Solution 2:[2]

Flatmap() also should work. Please make sure that your getRedirectToUrl method is not returning Mono.empty().

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Michael Berry
Solution 2 Spandy