Winster
Winster

Reputation: 1013

Multiple Mono and common subscriber

I am a newbie to reactive programming in Java. I plan to use spring-webclient instead of restclient as the latter is being decommissioned. I have a situation when I make several http post requests to different endpoints and the response structure is identical. With webclient code as below,

List<Mono<CommonResponse>> monolist = new ArrayList<>();
for(String endpoint : endpoints) {
  Mono<CommonResponse> mono = webClient.post()
     .uri(URI.create(endPoint))
     .body(Mono.just(requestData), RequestData.class)
     .retrieve()
     .bodyToMono(CommonResponse.class);
  monolist.add(mono);
}

I get a mono per request. As the response is common, I would like each mono to be subscribed a common method, but how can I distinguish the endpoints, assuming that the response data is not helping. Can I pass additional arguments to the method while subscribing?

Upvotes: 0

Views: 872

Answers (1)

Bartosz Kiebdaj
Bartosz Kiebdaj

Reputation: 141

You can do this in following way. If you have many monos you can treat team as flux which actually means that you have many of Mono. Then you can subscribe all of them with single method. To pass to subscribing method some extra arguments like information about endpoint, you can create extra object with additional information.

Flux<ResponseWithEndpoint> commonResponseFlux = Flux.fromIterable(endpoints)
                .flatMap(endpoint -> webClient.post()
                        .uri(URI.create(endpoint))
                        .body(Mono.just(requestData), RequestData.class)
                        .retrieve()
                        .bodyToMono(CommonResponse.class)
                        .map(response -> new ResponseWithEndpoint(response, endpoint)));
...
class ResponseWithEndpoint {
    CommonResponse commonResponse;
    String endpoint;

    public ResponseWithEndpoint(CommonResponse commonResponse, String endpoint) {
        this.commonResponse = commonResponse;
        this.endpoint = endpoint;
    }
}

Upvotes: 3

Related Questions