In many places there are recommendations to call Realm.getDefaultInstance()
in onCreate
method of the Activity
and call close
on Realm instance in onDestroy
(or in corresponding methods of presenter).
However, for me it would be cleaner to use Java's try-with-resources construct:
try (final Realm realm = Realm.getDefaultInstance()) {
// do stuff
}
Why cleaner? IMO it is easier to manage that narrow scope of realm
instance. Getting the instance in one moment of lifecycle and closing it in the another one, reminds me of old days with C++, when we had to worry about calling delete
in right moment.
The question is: is it a bad practice to use Realm in such way? Why none of tutorials mention it?
is it a bad practice to use Realm in such way?
No, this is recommended for background threads.
See https://realm.io/docs/java/latest/#closing-realm-instances in the official docs.
For UI thread, the onCreate()
/onDestroy()
is recommended, because if you close the local Realm instance, then the results that are bound to it become invalidated. A Realm needs to be open in order to provide the connection to the results in the Realm file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With