![](/img/trans.png)
[英]Is it possible to spy on suspend Android Room DAO functions with MockK
[英]Kotlin in Android - Suspend Functions in Room
我正在查看https://github.com/android/architecture-samples/tree/dev-dagger/app/src/main/java/com/example/android/architecture/blueprints/todoapp/data/source上的示例dev-dagger
分支的/local和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 调度程序中,在可读性和性能方面都是一种浪费。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.