Skip to content

Instantly share code, notes, and snippets.

@Zhuinden
Last active November 13, 2019 01:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Zhuinden/05c61f0f47dc9a9ead097de26a129bbd to your computer and use it in GitHub Desktop.
Save Zhuinden/05c61f0f47dc9a9ead097de26a129bbd to your computer and use it in GitHub Desktop.
Realm: say "no" to begin/commit and use execute (and use close!)
// SAY NO TO THIS
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction(); // NO
realm.copyToRealm(dog)
realm.commitTransaction(); // NO NO NO NO NO
// CLOSE THE REALM OH MY GOD WHY
// ----------------------
// SAY YES TO THIS
Realm realm = null;
try { // I could use try-with-resources here
realm = Realm.getDefaultInstance();
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
realm.insertOrUpdate(dog);
}
});
} finally {
if(realm != null) {
realm.close();
}
}
// OR IN SHORT (Retrolambda)
try(Realm realmInstance = Realm.getDefaultInstance()) {
realmInstance.executeTransaction((realm) -> realm.insertOrUpdate(dog));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment