Appnetic
Appnetic

Reputation: 11

When are you "done" with a realm?

I am currently working on a project with Expo and Realm. I want to integrate Realm into my App, but I don't quite get the line:

It is important to remember to call the close() method when done with a realm instance to avoid memory leaks.

-> https://docs.mongodb.com/realm/sdk/react-native/examples/open-and-close-a-realm/#close-a-realm

I mean: what is the definition of being done? As soon as my app is closed or as soon as I fetch the data I wanted to? Or should I open and close the realm all the time a user changes an entry?

I already did a lot of research and I know that it it quite expensive (resource wise) to start a new realm on a thread. But if there is already a realm running (UI Thread for Listeners) it isn't cost expensive at all.

Guess I am not sure on how to use realm within my code correctly.

Thanks in advance!

Upvotes: 1

Views: 232

Answers (1)

Pavel Yakimenko
Pavel Yakimenko

Reputation: 3254

It is widely depends on your use case. Sometimes it can be a lifetime of a screen (you add a new object in a database) or a lifetime of a feature (sequence of the user registration screens). In general try to avoid multiple calls to open Realm. For example, if you want to create multiple objects it's better

open Realm
in transaction {
    in loop {
        create object
    }
}
close Realm

Rather than

in loop {
    open Realm
    in transaction {
        create object
    }
    close Realm
}

If you need more precise answer you can add more details to your question.

Upvotes: 1

Related Questions