title: What is the best practice of managing realm instance in Clean Architecture?
body: <p>My project using clean architecture. In this situation, the UI layer is separate from Domain layer. So I think it would be better the UI layer doesn't own realm instance. As realm's doc recommend managing the realm instance in Activity's lifecycle, how should I deal with the realm instance then?</p>
  
  <p>To be more clear, my project is too heavy to change all objects extends <code>RealmObject</code>. So I use separate object to persistent data. When the api call finish, a business object convert to a realm object, opposite when query from realm. I create the method like this:</p>
  
  <pre><code>public void insert(T object){
      final Realm realm = RealmProvider.getRealm();
      realm.executeTransactionAsync(new Realm.Transaction() {
          @Override
          public void execute(Realm realm) {
              realm.copyToRealmOrUpdate(createRealmObject(object));
          }
      }, new Realm.Transaction.OnSuccess() {
          @Override
          public void onSuccess() {
              realm.close();
          }
      }, new Realm.Transaction.OnError() {
          @Override
          public void onError(Throwable error) {
              realm.close();
          }
      });
  }
  </code></pre>
  
  <p>Actually, it works fine. But below I don't know how to handle closing realm instance.</p>
  
  <pre><code>public Observable&lt;T&gt; queryAsync(Condition&lt;? extends RealmObject&gt; condition) {
      final Realm realm = RealmProvider.getRealm();
      return condition.getQuery(realm).findFirstAsync()
              .asObservable()
              .filter(new Func1&lt;RealmObject, Boolean&gt;() {
                  @Override
                  public Boolean call(RealmObject realmObject) {
                      return realmObject.isLoaded();
                  }
              })
              .map(new Func1&lt;RealmObject, T&gt;() {
                  @Override
                  public T call(RealmObject realmObject) {
                      return createObjectFromRealm(realmObject);
                  }
              });
  }
  </code></pre>