Search code examples
javaspringwebclientspring-webfluxproject-reactor

Convert traditional loop of invoking weclient into non blocking way


I am new to reactive programming and I want to transform the following code into non blocking way.

For the sake of simplicity, I created a sample pseudo code based from my original code. Any help will be appreciated.

 public Mono<Response> getResponse(List<Provider> providers) {

    for (Provider provider : providers) {
        Response response = provider.invokeHttpCall().block();

        if(response.getMessage() == "Success") {
            return Mono.just(response);
        }

        continue;
    }

    return Mono.empty();
}

provider.invokeHttpCall() method

    @Override
    public Mono<Response> invokeHttpCall(){
        WebClient webClient = WebClient.create();
        
        
        return webClient.post()
                .uri("/provider").accept(MediaType.APPLICATION_JSON)
                .retrieve()
                .bodyToMono(Response.class);
    }

I tried several tactics to implement this, but still no luck. Either all providers are invoked or I need to block the webclient thread.


Solution

  • Flux.fromIterable(providers)
        .concatMap(Provider::invokeHttpCall) // ensures providers are called sequentially
        .filter(response -> response.getMessage().equals("Success"))
        .next()