title: Persisting a network query and then checking whether another is needed with RxJava
body: <p>This seems like it should be simple, but I'm struggling with the correct way of flowing the RxJava chain. </p>
  
  <p>For instance, what isn't working is using <code>flatMap</code> to both persist data and check if another api query is needed:</p>
  
  <pre><code>return remote(amount = 2))
          .subscribeOn(Schedulers.io())
          .flatMap {
              insertAll(it)
              // Return an Observable&lt;Boolean&gt;, true if another api query is needed
              shouldGetMore(it)
          }
          .flatMap {
              if (it) remote(amount = 3)
              // If another query is not needed just return an empty observable
              else Observable.just(listOf())
          }
          .flatMapCompletable { insertAll(it) /* If another query was needed insert the result here */  }
          .observeOn(AndroidSchedulers.mainThread())
  </code></pre>
  
  <p>With the above, <code>insertAll()</code> isn't called the first time because the function <code>insetrtAll</code> is a completable and is therefore not subscribed to in the <code>flatMap</code>. Instead only <code>shouldGetMore()</code> is executed. Now, here is my question: </p>
  
  <p>For this to work I would need a <code>flatMapCompletable</code> at the beginning like so: </p>
  
  <pre><code>return remote(amount = 2))
          .subscribeOn(Schedulers.io())
          .flatMapCompletable { insertAll(it) }
          // ...
  </code></pre>
  
  <p>But if I do this then I no longer have access to the results of the first api query to check if I <code>shouldGetMore</code>. My only thought is making <code>insertAll</code> not a <code>Completable</code> but rather an <code>Observable</code> that returns what was persisted after the fact, thus allowing me to complete the chain.</p>
  
  <p>But this seems like an ugly approach, so I would be curious if anyone else had any other ideas?</p>
  
  <p>Thanks. </p>