title: RxJava Multithreading with Realm - Realm access from incorrect thread
body: <p><strong>Background</strong></p>
  
  <p>I am using Realm within my app. When data is loaded it then undergoes intense processing therefore the processing occurs on a background thread.</p>
  
  <p>The coding pattern in use is the Unit of Work pattern and Realm only exists within a repository under a DataManager. The idea here is that each repository can have a different database/file storage solution.</p>
  
  <p><strong>What I have tried</strong></p>
  
  <p>Below is an example of some similar code to what I have in my FooRespository class.</p>
  
  <p>The idea here is that an instance of Realm is obtained, used to query the realm for objects of interest, return them and close the realm instance. Note that this is synchronous and at the end copies the objects from Realm to an unmanaged state.</p>
  
  <pre><code>public Observable&lt;List&lt;Foo&gt;&gt; getFoosById(List&lt;String&gt; fooIds) {
  
      Realm realm = Realm.getInstance(fooRealmConfiguration);
  
      RealmQuery&lt;Foo&gt; findFoosByIdQuery = realm.where(Foo.class);
  
      for(String id : fooIds) {
  
          findFoosByIdQuery.equalTo(Foo.FOO_ID_FIELD_NAME, id);
          findFoosByIdQuery.or();
      }
  
      return findFoosByIdQuery
              .findAll()
              .asObservable()
              .doOnUnsubscribe(realm::close)
              .filter(RealmResults::isLoaded)
              .flatMap(foos -&gt; Observable.just(new ArrayList&lt;&gt;(realm.copyFromRealm(foos))));
  }
  </code></pre>
  
  <p>This code is later used in conjunction with the heavy processing code via RxJava:</p>
  
  <pre><code>dataManager.getFoosById(foo)
              .flatMap(this::processtheFoosInALongRunningProcess)
              .subscribeOn(Schedulers.io()) //could be Schedulers.computation() etc
              .subscribe(tileChannelSubscriber);
  </code></pre>
  
  <p>After reading the docs, my belief is that the above should work, as it is NOT asynchronous and therefore does not need a looper thread. I obtain the instance of realm within the same thread therefore it is not being passed between threads and neither are the objects.</p>
  
  <p><strong>The problem</strong></p>
  
  <p>When the above is executed I get</p>
  
  <blockquote>
    <p>Realm access from incorrect thread. Realm objects can only be accessed
    on the thread they were created.</p>
  </blockquote>
  
  <p>This doesn't seem right. The only thing I can think of is that the pool of Realm instances is getting me an existing instance created from another process using the main thread.</p>