JRahman
JRahman

Reputation: 23

How to chain a webclient call on each items from a list from the first call

I have two objects

CarParts {
    String   id
    WorkItem workItem
}

WorkItemResponse {
    List<WorkItem> resource; <- always contains one item.
}

I want to make a webclient on the car-parts which would return me a Mono<List<CarParts>> for each item in the list i want to use the id on the second call and then set Carparts's each WorkItem object with the result of the 2nd call

I also want to do a

Mono<List<Carparts>> carpartsmono = webclient.get.exchange();

Mono<WorkItemResponse> itemResponse = webclient.get().uri( item.id of carparts)

carpartsMono.flatmap(item -> item.stream().map(t -> t.setWorkItem(webclient.get("uri + 
     t.getId)).block().getResource().get(0)).collect(Collectors.AsList));

but I not able to find a solution.

Upvotes: 1

Views: 1879

Answers (1)

Goro
Goro

Reputation: 546

In reactive stack, one should try to make all code async, in your case one of the way is shown below :

Flux<CarPart> carPartFlux=
    webClient.get()
    .uri("/car-parts/{id}")
    .exchange()
    .bodyToFlux(CarParts.class)
    .map(carPart ->  {
        return
        webclient.get()
                 .uri("/workitems/" + cartPart.getWorkItemId())
                 .exchange()
                 .bodyToMono(WorkItemResponse.class)
                 .map(workitem ->  {
                      carPart.setWorkItem(workitem);
                      return carPart;
                 });
                 
    });

Now you can pass Mono of car part. Please try to avoid .block call as long as possible. Like if you are sending this to rest api client, you directly pass carPartMono in rest api response.

Also above code is sample and it can be improved further which depends on current execution conditions. Like can caching help. So you can start with this and monitor performance and take next steps.

Upvotes: 1

Related Questions