How to make chain of Mono/Flux and implement Retry in sping-webflux

673 views Asked by At

I have a scenario with reactive/async call. I am using spring-boot-starter-webflux and using webclient to make external HTTP calls. My scenario is I have to make a call to callA() and then check its response ResponseA. If its ResponseA is ok than exit and return ResponseA. Otherwise create second request requestB using ResponseA and make a call to callB(). Then check its response ResponseB. If it is ok then return ResponseA otherwise doRetry on callA().

public Mono<ResponseA> callA(Request1 requestA) {
    // calling service-A using webclient
}
public Flux<ResponseB> callB(Request2 requestB) { 
    // calling service-B using webclient but to create requestB, I need ResponseA.
}
1

There are 1 answers

4
Toerktumlare On BEST ANSWER

you just need to do some if-statements in a flatMap. Probably split it up into some better function names etc. No subscribing, no blocking.

callA(createNewRequest()).flatMap(response1 -> {

    // Validate response
    if(!isValidResponse(response)) {

        // if failed validation, create new request and do a new call
        var request = buildRequest(response);
        return callB(request).flatMap(response2 -> {

                // validate second response
                if(!isValidResponse(response2)) {

                     // failed validation return the first response.
                     return Mono.just(response1)
                }

                // otherwise recursively call again
                return callA(createNewRequest()); // Warning this can be an infinite loop
            }
    }

    // Validation passed
    return Mono.just(response);
}