CodeDevStack

Cache a Mono value from WebClient and repeat it

February 01, 2020

Let’s say you have a WebClient request and you want to zip the response with every value in a Flux stream.

Flux<String> myFlux = Flux.just("myFlux1", "myFlux2");

Mono<String> response = WebClient.create(url)
                                .get()
                                .bodyToMono(String.class);//myResponse

Flux.zip(response, myFlux, (a,b) -> a + " " + b);
//myResponse myFlux1

If you do as above, you will make the request only once and the flux will end after zipping the response with the first value of myFlux.

You could try adding a repeat() to response, but this will cause WebClient to be called repeatedly every single time you resubscribe to the Mono stream.

In order to make the call once and just repeat the value we need to use flatMapMany().

FlatMapMany transforms the item emitted by this Mono into a Publisher, then forward its emissions into the returned Flux.

Flux<String> myFlux = Flux.just("myFlux1", "myFlux2");

Mono<String> response = WebClient.create(url)
                                .get()
                                .bodyToMono(String.class);//myResponse

Flux<String> myResponseFlux = response
                .flatMapMany(res -> Mono.just(res).repeat());

Flux.zip(myResponseFlux, myFlux, (a,b) -> a + " " + b);
//myResponse myFlux1
//myResponse myFlux2

Doing it this way, we are creating a new publisher with the value of the WebClient response and repeating it. Now we’ll only reach the WebClient call once and myResponseFlux will return the Mono.just(res) over and over again.