Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I have to close realm on a per thread-basis, or per usage/class-basis?

Tags:

android

realm

If I have a MainActivity like this:

public class MainActivity extends AppCompatActivity
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Set up database
        RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this).build();
        Realm.deleteRealm(realmConfiguration); // Clean slate
        Realm.setDefaultConfiguration(realmConfiguration); // Make this Realm the default

        realm = Realm.getDefaultInstance();
    }

    @Override
    public void onDestroy() {
        realm.close();
        super.onDestroy();
    }
}

And I use realm.getDefaultInstance() in another class (same thread) like this:

public class ViewBookActivity extends Activity {
    private Realm realm;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_result);

        realm = Realm.getDefaultInstance();
    }
}

Should I then call realm.close() in onDestroy() in ViewBookActivity? Or is it sufficient to close it in MainActivity?

Realm documentation says:

Realm instances are reference counted, which means that if you call getInstance() twice in a thread, you will also have to call close() twice as well.

But I'm not sure if this applies to getDefaultInstance().

Also, is it OK to stick to Realm.getDefaultInstance(), even in other threads, if I close it when I'm done writing to it? I don't really understand the potential usage of Realm.getInstance(Context context).

Thanks

like image 539
tsorn Avatar asked Sep 26 '15 13:09

tsorn


1 Answers

Best practise is that if you open the Realm in onCreate you should close it again in onDestroy in all your activities as it means you reference count will reach 0 when all your activities have closed. So in your case: Yes, you should do it in both MainActivity and ViewBookActivity

With regard to Realm.getDefaultInstance(). That is just a shorthand for Realm.getInstance(myConfig), so you have to call close() on those as well.

Realm.getInstance(Context) is just a shorthand for Realm.getInstance(new RealmConfiguration.Builder(context).build()) and is intended to make it really easy to get started with Realm in small examples. If you plan to create a larger app you should create your configuration manually. But I agree it can be confusing and we should probably consider removing it all together.

like image 189
Christian Melchior Avatar answered Nov 18 '22 18:11

Christian Melchior