Android, using Realm singleton in Application

这一生的挚爱 提交于 2019-12-01 03:24:16

问题


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


来源:https://stackoverflow.com/questions/31800031/android-using-realm-singleton-in-application

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!