DBFlow - Async DB calls

450 Views Asked by At

In DBFlow's docs you can read that:

While generally saving data synchronous should be avoided, for small amounts of data it has little effect.

That's great! ...But, on the other hand there's this notice:

Doing operations on the main thread can block it if you read and write to the DB on a different thread while accessing DB on the main.


So if I understand this correctly, if I have for example android service that periodically reads/writes to db using async transactions (in separate thread) and user clicks a button in Activity that executes simple model.save() then the main thread of my android application would be blocked and app would 'freeze' until db is unlocked. Is that right?

If it is, the solution could be to place all db calls on async thread's queue, like:

interface AsyncResult {
    fun onResult(success: Boolean)
}

fun MyModel.save(callback: AsyncResult) {
    database<AppDatabase>().beginTransactionAsync { this.save() }
            .success { callback.onResult(true) }
            .error { _, _ -> callback.onResult(false)}
            .build()
            .execute()
}

and exeute it from Activity like:

myModel.save(object: AsyncResult {
    override fun onResult(success: Boolean) = if (success) showToast("got it")
})

But aren't the simple calls like save(), insert() wrapped in implicit transactions, so we end up with nested transactions? Not to mention all the boilerplate code on the model and view layers.

What is the proper way to deal with such a problem?

0

There are 0 best solutions below