Gerard Bosch
Gerard Bosch

Reputation: 688

Instantiating and closing Realm instances

I'm a bit confused about how/when/why to close the realm instances. In the whole course of my application I've never invoked .close() on my realm instance, because if I close it I am no longer able to use the realm objects I deal with. Maybe the point to close the realm instance would be in my Application onDestroy() in the same way I create my instance in my Application onCreate(). Actually I play with a singleton instance of Realm [*] created in my Application.

Is this (a Realm singleton) a good approach? and What can happen if I never close my Realm?

[*] In fact now I'm thinking in a Flywheight collection of Realm instances, storing an instance per thread instead, as now Service Intent came to play in my app and need access Realm from its thread. I think here (in Service Intent), I can close realm in onDestroy() as thread will be finished doing work.

Upvotes: 2

Views: 649

Answers (1)

Christian Melchior
Christian Melchior

Reputation: 20126

Realm handles caching internally and will make it as performant as possible. So you should not be afraid of calling Realm.getInstance(). The reason is that close() is required is that you might risk leaking memory which eventually will kill your app.

In short, you should not make a Realm singleton or other caching pattern yourself. You can read more about best practices for controlling the Realm lifecycle here: https://realm.io/docs/java/latest/#controlling-the-lifecycle-of-realm-instances

Note that Application.onDestroy() does not exists and Application.onTerminate() is not called for normal apps.

Upvotes: 1

Related Questions