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())
}
A suspending function is simply a function that can be paused and resumed at a later time. They can execute a long running operation and wait for it to complete without blocking. The syntax of a suspending function is similar to that of a regular function except for the addition of the suspend keyword.
This is the same executor that would be used by LiveData to do background work. Start using Room and coroutines in your app, the database work is guaranteed to be run on a non-UI Dispatcher. Mark your DAO method with the suspend modifier and call them from other suspend functions or coroutines!
BLOCKING: Function A has to be completed before Function B continues. The thread is locked for Function A to complete its execution. SUSPENDING: Function A, while has started, could be suspended, and let Function B execute, then only resume later. The thread is not locked by Function A.
A ViewModelScope is defined for each ViewModel in your app. Any coroutine launched in this scope is automatically canceled if the ViewModel is cleared. Coroutines are useful here for when you have work that needs to be done only if the ViewModel is active.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With