Android, using Realm singleton in Application

2020-03-19 04:59发布

问题:

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

回答1:

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();
    }
}


标签: android realm