title: RxJava2 with Room error handling - Database main thread exception
body: <p>I'm trying to retrieve items from a remote source, if this won't work (no internet) i'd like to retrieve cached items from a room database.
  I have created a new single for when the error happens and I've specified on what thread it should subscribe and observe on. I still this exception though:</p>
  
  <pre><code>java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
  </code></pre>
  
  <p>This is the method for retrieving the items:</p>
  
  <pre><code>public LiveData&lt;List&lt;Article&gt;&gt; getNewsArticles() {
      return LiveDataReactiveStreams.fromPublisher(
              newsService.getNewsArticles()
                      .subscribeOn(Schedulers.io())
                      .observeOn(AndroidSchedulers.mainThread())
  
                      .onErrorResumeNext(throwable -&gt;
                              Single.just(newsDao.findAllForNumber(AMOUNT_OF_ARTICLES_PER_PAGE))
                                      .subscribeOn(Schedulers.io())
                                      .observeOn(AndroidSchedulers.mainThread()))
  
                      .subscribeOn(Schedulers.io())
                      .observeOn(AndroidSchedulers.mainThread())
  
                      .doOnSuccess(newsArticles -&gt; Completable.fromAction(() -&gt;
                              newsDao.insertAll(newsArticles))
                              .subscribeOn(Schedulers.io()))
                      .toFlowable());
  }
  </code></pre>
  
  <p>LiveDataReactiveStreams converts it into a livedata object and handles the subscribtion, so my view only knows about livedata.</p>
  
  <p>I just can't seem to make the onErrorResumeNext call work on a background thread.</p>
  
  <p>Any help would be greatly appreciated!</p>
  
  <p><strong>ANSWER</strong></p>
  
  <p>I ended up solving tthe problem with the following code:</p>
  
  <pre><code>public LiveData&lt;List&lt;Article&gt;&gt; getNewsArticles() {
      return LiveDataReactiveStreams.fromPublisher(
              newsService.getNewsArticles()
                      .observeOn(Schedulers.io())
                      .doOnSuccess(newsArticles -&gt; newsDao.insertAll(newsArticles))
                      .onErrorResumeNext(throwable -&gt; Single.fromCallable(() -&gt; newsDao.findAllForNumber(AMOUNT_OF_ARTICLES_PER_PAGE)))
                      .toFlowable());
  }
  </code></pre>