Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine multiple greenDAO Tx operations into one transaction?

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 ?

like image 640
midnight Avatar asked Jan 15 '13 17:01

midnight


1 Answers

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();
    }
}
like image 183
Markus Junginger Avatar answered Oct 04 '22 01:10

Markus Junginger