Reputation: 514
I'm using Realm for my React Native app. I'm making Realm instances available to my components like this, as shown in the official example app:
export default new Realm({schema: [Todo, TodoList]});
.
When I subsequently ran tests with Jest, I realized that the process didn't finish as long as I wouldn't call
afterAll(() => {
realm.close();
});
at the end of the test suite.
This made me think about if and when I should call realm.close()
in the production code. What are the consequences of not calling close? If recommended, what would be the best way to close Realm instances?
Upvotes: 18
Views: 9648
Reputation: 17556
some good, and straight-to-the-point references:
Realm
instances are reference counted—if you callgetInstance
twice in a thread, you need to callclose
twice as well. This allows you to implementRunnable
classes without having to worry about which thread will execute them: simply start it withgetInstance
and end it with close.
when executing transactions (generally in background threads):
Realm
instanceexecuteTransaction
close()
afterwardsfor example:
Realm.getDefaultInstance()
// use will close realm after the transaction is finished/failed
.use { realm ->
// DO NOT execute read/write operations outside of a transaction...
// because it will lead to stale reads, exceptions, and other problems
realm.executeTransaction { realm ->
// do things in the transaction (both reading & writing)
}
}
On the main/UI/looper/handler threads, keep an instance of Realm
open, because you're usually interested in listening to changes in RealmResults
obtained from that Realm
instance:
Realm
instance is created/obtained when the application is visibleclose()
d.for example:
// in chronological order....on main UI thread
// application starts....
val realm = Realm.getDefaultInstance()
// user navigating to some view...
// execute a query that will return results that we're interested in displaying
val realmResults = realm.where(Entity::class.java).findAllAsync()
// need to hold a strong reference to the listener, otherwise it may stop
// receiving callbacks from Realm, because Realm only holds weak references to
// registered listeners
val listener = RealmChangeListener<RealmResults<Entity>> { assessments ->
// update UI
}
// add the listener to the query
realmResults.addChangeListener(listener)
// user shutting down app...close main thread's realm
realm.close()
Upvotes: 3
Reputation: 10588
realm.close()
is used when you are done with your current schema. In Realm api page it says the following:
close(): Closes this Realm so it may be re-opened with a newer schema version. All objects and collections from this Realm are no longer valid after calling this method.
If you don't want to change your schema, you don't have to worry about close
method.
Full reference here: Realm close method.
Upvotes: 19