gpt4 book ai didi

android - Android 中的 Kotlin - 暂停房间中的功能

转载 作者:行者123 更新时间:2023-12-02 12:01:07 26 4
gpt4 key购买 nike

我在查看样本 https://github.com/android/architecture-samples/tree/dev-dagger/app/src/main/java/com/example/android/architecture/blueprints/todoapp/data/source/localdev-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 线程上运行。但是房间请求 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 调度程序中,在可读性和性能方面都是一种浪费。

关于android - Android 中的 Kotlin - 暂停房间中的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60238020/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com