Is it a good practice to use Realm with try-with-resources?

Piotr Aleksander Chmielowski :

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?

EpicPandaForce :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=461184&siteId=1