Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 448
Piotr Aleksander Chmielowski Avatar asked May 12 '17 10:05

Piotr Aleksander Chmielowski


1 Answers

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.

like image 172
EpicPandaForce Avatar answered Oct 22 '22 00:10

EpicPandaForce