Good practice using Realm with trial resources?

In many places, there are recommendations for calling the Realm.getDefaultInstance() method in onCreate Activity and calling close on a Realm instance in onDestroy (or in the corresponding presenter methods).

However, it would be easier for me to use the Java try-with-resources construct:

 try (final Realm realm = Realm.getDefaultInstance()) { // do stuff } 

Why is it cleaner? IMO is easier to manage with a narrow volume of realm instance. Getting an instance at one point in the life cycle and closing it at another reminds me of the old days with C ++, when we had to worry about calling delete at the right time.

Question: Is it wrong to use Realm in this way? Why does not one of the lessons mention this?

+5
source share
1 answer

Is it wrong for you to use the kingdom in this way?

No, this is recommended for background threads .

See https://realm.io/docs/java/latest/#closing-realm-instances in the official docs.


onCreate() / onDestroy() recommended for the user interface onCreate() , since if you close the local instance of Realm, the results associated with it become invalid. Realm must be open in order to connect to the results in the Realm file.

+6
source

All Articles