Last active
November 13, 2019 01:38
-
-
Save Zhuinden/05c61f0f47dc9a9ead097de26a129bbd to your computer and use it in GitHub Desktop.
Realm: say "no" to begin/commit and use execute (and use close!)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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