Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

When to use executeTransaction() instead of beginTransaction(); #4217

Closed
Muddz opened this issue Feb 21, 2017 · 5 comments
Closed

When to use executeTransaction() instead of beginTransaction(); #4217

Muddz opened this issue Feb 21, 2017 · 5 comments
Labels

Comments

@Muddz
Copy link

Muddz commented Feb 21, 2017

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?

@Zhuinden
Copy link
Contributor

executeTransaction() is equivalent to

try {
    realm.beginTransaction();
    // body of executeTransaction
    realm.commitTransaction();
} catch(Exception e) { 
    if(realm.isInTransaction()) {
         realm.cancelTransaction();
    }
    throw new RuntimeException(e);
}

@cmelchior
Copy link
Contributor

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.

@Zhuinden
Copy link
Contributor

Or if you need to cancel the transaction manually at some point for some reason.

@aalap03
Copy link

aalap03 commented Feb 16, 2018

@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?

@Zhuinden
Copy link
Contributor

@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.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Mar 16, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Development

No branches or pull requests

5 participants