Marcus
Marcus

Reputation: 162

Correctly handling Realm intances on Android

I am using Realm for my Android app and I have noticed that the disk usage increases pretty much every time I open the app. The reason for this is that I never really close a realm. I have about 5 different activities using data from Realm and a singleton class which handles all the interatction with Realm. I chose having only 1 class because it removed a lot of duplicate code. As I am using a singleton class with observers (activities) I don't know when to close a realm or how to avoid creating multiple instances.

Right now I am using Realm.getIntanceAsync() every time I need to access data on the server but to my understanding that is not optimal and obviously bad handling of Realm instances.

How would I structure the usage of Realm if I have separate activities that all need updated data from Realm without storing multiple copies/versions of a single Realm? I want to try to avoid code duplication if possible but most examples I have seen of Realm on Android has been where a realm instance is opened in each activity and then closed in the activity's onDestroy(). I would also prefer having a smaller amount of classes dependent on Realm rather than the entire application.

EDIT: I am using a synchronized Realm with the Realm Object Server.

Upvotes: 0

Views: 336

Answers (1)

caketuzz
caketuzz

Reputation: 126

You don't need to have one class only to handle Realm management. Realm already manages multiple instances so it is perfectly safe.

Not closing realm instances is bad practice and you should avoid doing so. Actually there are two different ways:

  • either get a realm instance whenever you need it and then close it asap. You may get into trouble if running async requests.

  • or get an instance in the onCreate/onResume method, store it as a class member and close it in the onDestroy/onPause accordingly.

However, creating multiple instances of Realm is not a reason for the disk usage to increase. You may rather check if you set your primary keys correctly. Because if you don't pay attention, data could be stored multiple times, resulting in orphaned data which will not be replaced and hence grow up your local database.

Upvotes: 1

Related Questions