Search code examples
androidkotlinandroid-roomkotlin-coroutinessuspend

Kotlin in Android - Suspend Functions in Room


I was looking at the sample at https://github.com/android/architecture-samples/tree/dev-dagger/app/src/main/java/com/example/android/architecture/blueprints/todoapp/data/source/local of the dev-dagger branch and in the TasksLocalDataSource.kt file they have the following method:

override suspend fun getTasks(): Result<List<Task>> = withContext(ioDispatcher) {
        return@withContext try {
            Success(tasksDao.getTasks())
        } catch (e: Exception) {
            Error(e)
        }
}

By using withContext with an IO as dispatcher, they want the coroutine to run on an IO thread. But the Room request tasksDao.getTasks() inside the method is a suspend function. And in the codelab at https://codelabs.developers.google.com/codelabs/kotlin-coroutines/#8, they say that Room takes care of running the request (here: getTasks() ) on a background thread when it is a suspend function which is the case here. So, isn't too much to use also a withContext(ioDispatcher) ? Could I not rewrite the method above also like the following way ? :

override suspend fun getTasks(): Result<List<Task>> {
         return Success(tasksDao.getTasks())
}

Solution

  • Yes, this is exactly what you should write. There still appears to be a lot of legacy in the docs, from the time before they introduced suspendable Room calls. It is a waste both in terms of readability and performance to force a suspendable function call into the IO dispatcher.