存储库内的协程范围 class

Coroutine Scope inside repository class

假设我有一个 Dto 列表,我想遍历它们并设置一些值,然后 insert/update 它们到我的 Room 数据库。所以从我的 ViewModel 我调用存储库 class,运行 里面的循环然后我调用 dao.insertItems(list).


fun updateItems(itemList: List<ItemDto>) {
        val readDate = DateUtils.getCurrentDateUTCtoString()
        ???SCOPE???.launch(Dispatchers.IO) {
            for (item in itemList)
                item.readDate = readDate
            itemDao.updateItems(itemList)
        }
    }

问题是我必须在存储库中使用哪种 courtineScope class。 我是否必须使用 Dispatchers.Main.. 创建一个 repositoryScope?也许是 GlobalScope..?

您应该将存储库 API 编写为 suspend 函数,就像这样

suspend fun updateItems(itemList: List<ItemDto>) = withContext(Dispatchers.IO) {
    val readDate = DateUtils.getCurrentDateUTCtoString()
    for (item in itemList)
        item.readDate = readDate
    itemDao.updateItems(itemList)
}

编辑:如果你需要这个 运行 即使在 viewmodel 被销毁后,用 NonCancellable,

启动它
suspend fun updateItems(itemList: List<ItemDto>) = withContext(Dispatchers.IO + NonCancellable) {
    val readDate = DateUtils.getCurrentDateUTCtoString()
    for (item in itemList)
        item.readDate = readDate
    itemDao.updateItems(itemList)
}

在存储库中创建您的方法 suspend fun 并使用 withContext(Dispatchers.IO)

例如

suspend fun updateItems() = withContext(Dispatchers.IO) {
    //you work...
}