I'm using Dagger 2 to provide a singleton Realm instance for the whole app (all data access objects use a single realm). However, as far as I know, Realm can have multi-instance using Realm.getInstance() and we have to close each instance when we're done with it as presented by the Realm docs:
/**
* Closes the Realm instance and all its resources.
* <p>
* It's important to always remember to close Realm instances when you're done with it in order not to leak memory,
* file descriptors or grow the size of Realm file out of measure.
*
* @throws IllegalStateException if attempting to close from another thread.
*/
@Override
public void close() {
if (this.threadId != Thread.currentThread().getId()) {
throw new IllegalStateException(INCORRECT_THREAD_CLOSE_MESSAGE);
}
if (realmCache != null) {
realmCache.release(this);
} else {
doClose();
}
}
My question is: should I use a singleton Realm instance as I did, or create a realm instance for each Activity / Fragment and close it using realm.close() at onDestroy()?