我正在查看https://github.com/android/architecture-samples/tree/dev-dagger/app/src/main/java/com/example/android/architecture/blueprints/todoapp/data/source/local分支的dev-dagger
处的示例,并且在TasksLocalDataSource.kt
文件中,它们具有以下方法:
override suspend fun getTasks(): Result<List<Task>> = withContext(ioDispatcher) {
return@withContext try {
Success(tasksDao.getTasks())
} catch (e: Exception) {
Error(e)
}
}
[通过将withContext
与IO作为调度程序,他们希望协程在IO线程上运行。但是该方法中的Room请求tasksDao.getTasks()
是暂停函数。在https://codelabs.developers.google.com/codelabs/kotlin-coroutines/#8的代码实验室中,他们说Room
负责在后台线程上运行请求(此处为getTasks()
),因为它是一个挂起函数(在这种情况下)。因此,使用withContext(ioDispatcher)
也不是太多吗?我不能像下面的方式那样重写上面的方法吗? :
override suspend fun getTasks(): Result<List<Task>> {
return Success(tasksDao.getTasks())
}
是的,这正是您应该写的。从文档引入可挂起的Room通话开始到现在,文档中似乎仍然有很多遗留物。强制将可挂起的函数调用放入IO调度程序在可读性和性能上都是浪费。