Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Android Realm – Transaction Management

— Unlike read operations, write operations in Realm must be wrapped in transactions.
— At the end of a write operation, you can either commit the transaction or cancel it.

Realm realm = Realm.getDefaultInstance(); // Obtain a Realm instance
realm.beginTransaction(); // Begin Transaction
User user = realm.createObject(User.class); // Create a new object
user.setName("Prasanna");
user.setCountry("India");
realm.commitTransaction(); // Commit Transaction
OR to discard the changes by cancelling the transaction
// realm.cancelTransaction(); // Cancel Transaction

Transaction Block

Instead of manually keeping track of beginTransaction, commitTransaction, and cancelTransaction, you can use the executeTransaction method, which will automatically handle begin, commit, and cancel if an error happens.

try (Realm realm = Realm.getDefaultInstance()) {
 realm.executeTransaction(real -> {
  User user = realm.createObject(User.class);
  user.setName("Prasanna");
  user.setCountry("India");
 });
}

Asynchronous Transaction

Since transactions are blocked by other transactions, you might want to write on a background thread to avoid blocking the UI thread. By using an asynchronous transaction, Realm will run that transaction on a background thread.

Realm realm = Realm.getDefaultInstance();
realm.executeTransactionAsync(new Realm.Transaction() {
 @Override
 public void execute(Realm real) {
  User user = real.createObject(User.class);
  user.setName("Prasanna");
  user.setCountry("India");
 }
}, new Realm.Transaction.OnSuccess() {
 @Override
 public void onSuccess() {
  // Transaction was a success.
 }
}, new Realm.Transaction.OnError() {
 @Override
 public void onError(Throwable error) {
  // Transaction failed and was automatically canceled.
 }
});


This post first appeared on Javac, please read the originial post: here

Share the post

Android Realm – Transaction Management

×

Subscribe to Javac

Get updates delivered right to your inbox!

Thank you for your subscription

×