title: Realm, network operations, subscribing and observing on different threads with RxJava
body: <p>I need to :</p>
  
  <ul>
  <li>Fetch some data from an API on a background thread</li>
  <li>Display the data on the UI </li>
  <li><p>Save to Realm. </p>
  
  <pre><code>fetchItemsFromServer().subscribeOn(Schedulers.io())
          .observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1&lt;ItemList&gt;() {
      @Override
      public void call(ItemList items) {
  
          displayItems(items);
  
          try {
              realm.beginTransaction();
              realm.copyToRealmOrUpdate(itemList);
              realm.commitTransaction();
              Logger.v("Realm ", "Copied list object to realm");
          } catch (Exception e) {
              Logger.e("Realm Something went wrong ", e);
              realm.cancelTransaction();
          }
  
      }
  }
  </code></pre></li>
  </ul>
  
  <p>This throws an error : <strong><em>realm accessed from incorrect thread</em></strong> </p>
  
  <p>I have 4 tabs fetching different messages at the same time. </p>
  
  <p>fetchItemsFromServer() is an intensive call and confining this call to one thread is not good. I need this flexibility.</p>
  
  <p>Has anyone found any workarounds using realm this way?</p>
  
  <p>Most examples e.g tend to be focused on fetching from Realm vs working with network operations:</p>
  
  <p>Example below:</p>
  
  <p>Rxjava - <a href="https://realm.io/news/realm-java-0.87.0/" rel="nofollow">https://realm.io/news/realm-java-0.87.0/</a></p>
  
  <p>Using realm with RxJava - <a href="https://realm.io/news/using-realm-with-rxjava/" rel="nofollow">https://realm.io/news/using-realm-with-rxjava/</a> (previous solution but performance drawbacks) </p>
  
  <p>My Realm is provided by a database module through dependency injection (Dagger 2)</p>
  
  <pre><code>@Module
  public class DatabaseModule {
  
      public static final String REALM_FILE_NAME = "Realm name";
  
      @Provides
      Realm providesRealmInstance(Context context) {
      return Realm.getInstance(
              new RealmConfiguration.Builder(context)
                      .name(REALM_FILE_NAME)
                      .build());
      }
  }
  </code></pre>