Home > other >  Does Android Room wait for withTransaction block to finish before proceeding to next line
Does Android Room wait for withTransaction block to finish before proceeding to next line

Time:11-06

class MyViewModel(private val db: AppDatabase): ViewModel() {

    suspend fun insertAndRead(pages: List<Page>) {
        db.withTransaction {
            db.pageDao().insertAll(pages)    
        }
        val pagesInserted = db.pageDao().selectAll()
    }
}

I'm curious about the Room handles the withTransaction block.

Let's say with the code example above. Does Room wait for the withTransaction block to finish running, then go to then next line?

Or it simply runs the withTransaction block inside a coroutine, then starting the next line immediately without waiting for the withTransaction block to complete?

CodePudding user response:

withTransaction() is a suspend function. Suspend functions generally wait by suspending, they are synchronous to their callers, they don't schedule asynchronous operations.

So the answer is: yes, it waits for the inner block to finish executing.

  • Related