Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android, using Realm singleton in Application

Tags:

android

realm

I'm new to Realm, I'm wondering whether it's good practice to just have one Realm instance in Application object, use it across all cases needed in the app, and only close it in onDestroy of the Application class.

Thanks

like image 574
EyeQ Tech Avatar asked Aug 04 '15 03:08

EyeQ Tech


People also ask

Where do we use singleton class in Android?

The Singleton Pattern is a software design pattern that restricts the instantiation of a class to just “one” instance. It is used in Android Applications when an item needs to be created just once and used across the board. The main reason for this is that repeatedly creating these objects, uses up system resources.

What is realm Nosql database in Android?

Realm is an object database that is simple to embed in your mobile app. Realm is a developer-friendly alternative to mobile databases such as SQLite and CoreData. Before we start, create an Android application. Feel free to skip the step if you already have one.


1 Answers

There is nothing inherently wrong with keeping the Realm on the UI thread open and not closing it (note there is no OnDestroy on Application)

However you should keep the following in mind:

1) Realm can handle the process getting killed just fine, which means that forgetting to close Realm is not dangerous to your data.

2) Not closing Realm when the app goes in the background means you will be more likely to get killed by the system if it gets low on resources.

As Emanuele said. Realm use thread local caches internally in order to not open more Realms than needed. This means that you shouldn't care how many times you call Realm.getInstance() as in most cases it will just be a cache lookup. It is however good practise to always have a corresponding close method as well.

// 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();
    }
}
like image 156
Christian Melchior Avatar answered Sep 18 '22 11:09

Christian Melchior