axpira
axpira

Reputation: 11

SpringBoot: How to call a API chain using reactive programming?

I want to call a Mono in middle of another Flux streams sending a parameter of Flux to mono. I'm using WebClient from SpringBoot.

I tried this:

WebClient client = WebClient.create();
    client.get().uri("http://localhost:8081/api/{param1}", param1)
        .retrieve()
        .bodyToFlux(String.class)
        .zipWith(
            client.get().uri("http://localhost:8082/api/{param2}", param2)
            .retrieve()
            .bodyToMono(String.class);
        )
        .map(tuple -> {
          return tuple.getT1() + tuple.getT2();
        })

But how can I send to param2 the return of first API call? And get both response after? The first API return many values and for each value I need to call the second API.

Thanks

Upvotes: 0

Views: 2017

Answers (1)

axpira
axpira

Reputation: 11

This is how I did it:

WebClient client = WebClient.create();
client.get().uri("http://localhost:8081/api/{param1}", param1)
    .retrieve()
    .bodyToFlux(String.class)
    .flatMap(
        response1 -> 
            client.get().uri("http://localhost:8082/api/{param2}", response1)
                .retrieve()
                .bodyToMono(String.class)
                .map(response2 -> new Response(response1, response2))
     )
     , Response.class
     )

Upvotes: 1

Related Questions