6

My application consumes remote REST API and populates local db with greenDao. I have a service with AsyncTask class:

@Override
protected Void doInBackground(Void... params) {
    insert100RowsIntheFirstTable();
    insert100RowsIntheSecondTable();
}

Inside each insert-method I have insertOrReplaceInTx, which I use primarily for performance gain.

What I need is to abandon results if any of the methods fails to retrieve data. It's supposed to be done through the same transaction.

I wonder if it's right to surround my insert-method calls with mDaoSession.callInTx(callable) while having insertOrReplaceInTx inside the methods. Am I right?

Additionally, how do I abandon transaction in case exception is raised - is it done automatically by means of greenDao ?

Markus Junginger
  • 6,950
  • 31
  • 52
midnight
  • 3,420
  • 3
  • 36
  • 58

1 Answers1

9

Yes use callInTx if your code can throw a exception (if not you can also consider runInTx. Android's SQLite API takes care of those "nested" transactions.

After all, callInTx is just some lines of convenience if you look at the source code:

public <V> V callInTx(Callable<V> callable) throws Exception {
    db.beginTransaction();
    try {
        V result = callable.call();
        db.setTransactionSuccessful();
        return result;
    } finally {
        db.endTransaction();
    }
}
Markus Junginger
  • 6,950
  • 31
  • 52
  • 1
    If the first insertInTx succeeds and the second one fails, won't the first set of objects remain in the session cache even though the DB rolled back the transaction? – Monstieur May 15 '14 at 03:57