Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close realm opened by Realm.getDefaultInstance?

Tags:

android

realm

I am using realm to store and retrieve data. Usually when we open a realm to store some data we do like:

Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
// Copy the object to Realm
realm.copyToRealm(myObject);
realm.commitTransaction();
realm.close();

in the above case I am closing the realm.

But when I am retrieving some data like:

RealmResults<MyClass> results = Realm.getDefaultInstance().where(MyClass.class).findAll();

How do I close this realm? Does it need to be closed?

like image 854
Nongthonbam Tonthoi Avatar asked May 09 '16 10:05

Nongthonbam Tonthoi


1 Answers

Doing it as a one-liners means you cannot close the Realm, so I would advice against that.

Not closing the Realm will in the best case cause you to leak memory and have a higher chance of being killed by the system if the in the background. Worst case you will see a high increase in disk usage because Realm has to keep track of all versions of opened Realm instances (due to being a MVCC database).

I would highly advice using your first pattern. For more information about controlling the Realm instances you can read this: https://realm.io/docs/java/latest/#realm-instance-lifecycle and this https://realm.io/news/threading-deep-dive/

like image 174
Christian Melchior Avatar answered Oct 26 '22 23:10

Christian Melchior