title: Paginate Observable results without recursion - RxJava
body: <p>I've got a pretty standard API pagination problem which you can handle with some simple recursion. Here's a fabricated example:</p>
  
  <pre><code>public Observable&lt;List&lt;Result&gt;&gt; scan() {
      return scanPage(Optional.empty(), ImmutableList.of());
  }
  
  private Observable&lt;?&gt; scanPage(Optional&lt;KEY&gt; startKey, List&lt;Result&gt; results) {
      return this.scanner.scan(startKey, LIMIT)
              .flatMap(page -&gt; {
                  if (!page.getLastKey().isPresent()) {
                      return Observable.just(results);
                  }
                  return scanPage(page.getLastKey(), ImmutableList.&lt;Result&gt;builder()
                          .addAll(results)
                          .addAll(page.getResults())
                          .build()
                  );
              });
  }
  </code></pre>
  
  <p>But this can obviously create a massive callstack. How can I do this imperatively but maintain the Observable stream?</p>
  
  <p>Here's an imperative blocking example:</p>
  
  <pre><code>public List&lt;Result&gt; scan() {
      Optional&lt;String&gt; startKey = Optional.empty();
      final ImmutableList.Builder&lt;Result&gt; results = ImmutableList.builder();
  
      do {
          final Page page = this.scanner.scan(startKey);
          startKey = page.getLastKey();
          results.addAll(page.getResults());
      } while (startKey.isPresent());
  
      return results.build();
  }
  </code></pre>