Realm-java: When to use executeTransaction() instead of beginTransaction();

Created on 21 Feb 2017  路  5Comments  路  Source: realm/realm-java

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?

T-Help

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 using beginTransaction() is normally if you want to have some custom error handling.

All 5 comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

David-Kuper picture David-Kuper  路  3Comments

bryanspano picture bryanspano  路  3Comments

iAbdulaziz picture iAbdulaziz  路  3Comments

wezley98 picture wezley98  路  3Comments

gpulido picture gpulido  路  3Comments