Android using Realm singleton in app

I am new to Realm, I am wondering if it is simple to have one instance of Realm in the Application object, use it in all cases necessary in the application, and only close it in the onDestroy of the Application class.

thanks

+4
source share
1 answer

Essentially, there is nothing wrong with keeping Realm in the UI thread open and not closing it (note: there is no OnDestroy on Application )

However, you should remember the following:

1) The kingdom can handle a process that kills just fine, which means that forgetting to close the Kingdom is not dangerous for your data.

2) Without closing Realm when the application is running in the background, you will most likely be killed by the system if it becomes less resources.

As Emanuele said. Realm uses local local streams inside to not open more Realms than necessary. This means that you don't care how many times you call Realm.getInstance() , since in most cases it will just be a cache search. However, it is good practice to always use the appropriate close method.

 // This is a good pattern as it will ensure that the Realm isn't closed when // switching between activities, but will be closed when putting the app in // the background. public class MyActivity extends Activity { private Realm realm; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); realm = Realm.getDefaultInstance(); } @Override protected void onDestroy() { realm.close(); } } 
+8
source

All Articles