Android, using Realm singleton in Application

北城余情 提交于 2019-12-01 05:17:28

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