Search code examples
springrequestreactivesequential

Spring5 - Reactor API - Sending sequential requests and getting the responses as a String


I am sending sequential request and trying to print the response as a string:

  Flux.fromIterable(keywordsList).map(i -> client.get()
              .uri("/hello?now-word=" + i)
              .accept(MediaType.APPLICATION_JSON)
              .retrieve()
              .bodyToMono(String.class))
              .subscribe(item -> System.out.println("item: " + item.toString()));

But this is what I am getting:

  item: MonoFlatMap
  item: MonoFlatMap
  item: MonoFlatMap
  item: MonoFlatMap
  item: MonoFlatMap
  item: MonoFlatMap
  item: MonoFlatMap
  item: MonoFlatMap
  item: MonoFlatMap
  item: MonoFlatMap
  item: MonoFlatMap
  item: MonoFlatMap

I tried to use FlatMapIterable, but I don't know how to use it correctly.


Solution

  • As of now, I am sending the requests in a loop. Here is the code and this works for me:

      for(int i = 3; i <= len; i++) {
            String searchStr = searchString.substring(0, i);
    
            Mono<ClientResponse> result = client.get()
                    .uri(autocompleteUri + searchString)
                    .accept(MediaType.APPLICATION_JSON)
                    .exchange();
    
            String result1 = ">> result = " + result.flatMap(res -> res.bodyToMono(String.class)).block();
    
    
        }
    

    But I would like to know the different ways we can do this. Here is the blog about this project:

    blog