There are 2 ways to write a transaction to the realm objects which are: executeTransaction() and manual call with beginTransaction();, commitTransaction()
When should either be used?
For a more specific usecase. I have an app containing a list where the user can add many items to that list, which write method should be used here?
executeTransaction() is equivalent to
try {
realm.beginTransaction();
// body of executeTransaction
realm.commitTransaction();
} catch(Exception e) {
if(realm.isInTransaction()) {
realm.cancelTransaction();
}
throw new RuntimeException(e);
}
Like @Zhuinden hints at. You should in most cases use executeTransaction() since it will handle errors for you. The only reason for using beginTransaction() is normally if you want to have some custom error handling.
Or if you need to cancel the transaction manually at some point for some reason.
@Zhuinden
try {
realm.beginTransaction();
// body of executeTransaction
realm.commitTransaction();
} catch(Exception e) {
if(realm.isInTransaction()) {
realm.cancelTransaction();
}
throw new RuntimeException(e);
}
Based on that, Doesrealm.closealso being taken care of by .executeTransaction ? Or we will have to mention it in finally?
@aalap03 i have previously defined a helper function like
public static void doInTransaction(Realm.Transaction transaction) {
try(Realm realm = Realm.getDefaultInstance()) {
realm.executeTransaction(transaction);
}
}
But realm.executeTransaction doesn't close the Realm.
realm.executeTransactionAsync opens a Realm on a background thread, and also closes that instance on that background thread.
Most helpful comment
Like @Zhuinden hints at. You should in most cases use
executeTransaction()since it will handle errors for you. The only reason for usingbeginTransaction()is normally if you want to have some custom error handling.