title: Spring Reactive - collect a sequence of paged results as a Mono of all results
body: <p>In my REST service I must call another REST service multiple times to get all the pages of the result list. The request contains a <code>from</code> field which I need to increase with every request. The response contains a <code>totalResults</code> field - when I've read all results I need to stop calling the other service, collect all the results from all calls and produce one <code>Mono&lt;List&lt;Result&gt;&gt;</code> response.</p>
  
  <p>This is what I had so far:</p>
  
  <pre><code>@Getter
  public class Request {
      private int from;
      private int size = 1000;
      private String type;
  
      public Request(String type, int from) {
          this.type = type;
          this.from = from;
      }
  }
  
  @Getter
  @Setter
  public class Response {
      private Integer totalResults;
      private Integer size;
      private Integer from;
      private List&lt;Result&gt; results;
  }
  
  public Mono&lt;List&lt;Result&gt;&gt; findByType(String type) {
      return Flux.generate(
              () -&gt; new Request(type, 0),
              (Request request, SynchronousSink&lt;List&lt;Result&gt;&gt; sink) -&gt; {
                  Response response = find(request).block();
                  sink.next(response.getResults());
                  int nextFrom = response.getFrom() + response.getSize();
                  if (nextFrom &gt;= response.getTotalResults()) {
                      sink.complete();
                  }
                  return new Request(type, nextFrom);
              })
              .flatMap(Flux::fromIterable)
              .collectList();
  }
  
  private Mono&lt;Response&gt; find(Request request) {
      return webClient
              .post()
              .uri("/search")
              .syncBody(request)
              .retrieve()
              .bodyToMono(Response.class);
  }
  </code></pre>
  
  <p>It works in a test using <code>MockWebServer</code> and <code>StepVerifier</code> but fails in production with</p>
  
  <pre><code>java.lang.IllegalStateException: block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-nio-2
  </code></pre>
  
  <p>How can I do it the correct reactive way?</p>