What is the best practice regarding opening, closing, and creating realms?

Is it a bad idea to open the realm when I enter a certain screen (where it is actually used) and close it when the screen is popped? Is there any performance implications other than the latency of opening the realm on entering the screen? I must mention that I have the realm encrypted too.

In another note, What if I did that in another isolate? What is the best practice to using realms in isolates?

You can open the realm as needed in a specific screen, but you are right that keeping it open and using it will lead to a better performance. Keeping the realm open is preferred. Al;so when a realm.write() call completes your objects are already persisted so you don’t need to open/close the realm for that.

We advise to use the main isolate when using Realm. Realm is designed to be used in the main isolate with same for using the Realm objects where needed. You can work with Realm from any isolate but this means you can not work with the Realm objects in the main isolate and you can not get notification changes etc.

Thanks for your answer! I’m actually concerned with memory usage. Do you have any advice for me? Do you think I should make the trade off (close the realm and release memory fast I mean)? I could just warm up (open the realm just before it is used to minimize opening time).

Realm is designed to be used on mobile devices with as little memory as possible. All object properties are lazily read and not kept in memory. Just use the Realm in the main isolate , preferably opening it only once. You can pass around Realm objects and if you want to update them just wrap the setters in a realm.write call. This is the most optimal way of using Realm.
Closing eagerly the Realm will not lead to saving much memory, if at all.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.