2

Are Room Database queries async? And if so, for lack of a better term, is something like this async/race condition safe?

fun insertThingAsync(thing: Thing) = async(Dispatchers.IO) {
  try {
    dao.deleteAllThings()
    dao.insertThing(thing)
  }
  catch (e: Throwable) {
    // Stuff
  }
}

In other words, is it possible, in this case, for the dao to attempt to insert the thing before dao.deleteAllThings() completes, and therefore have the chance of deleting the newly inserted thing as well?

If so, what are ways you all handle things like this to make sure you do not try to insert until the delete is complete?

I'm also wondering about the same use case with roomDatabase.clearAllTables, because of conversations in this thread.

TJ Olsen
  • 323
  • 2
  • 15

1 Answers1

5

They are not async If they are plain @Delete and @Insert DAO methods, then they should be serialized naturally, as those methods are executed synchronously.

The only place where Room does asynchronous stuff is on @Query with a reactive return value (LiveData, Flowable, etc.).

There could be issues from concurrent modifications when starting multiple transactions/operations in different threads or from different Schedulers/Dispatchers.

In your case you have one coroutine in which they will run sequentially. So it is safe to think you will do delete first and then insert.

You can also create Transaction to execute multiple queries.

https://developer.android.com/reference/androidx/room/Transaction

Rainmaker
  • 10,294
  • 9
  • 54
  • 89