让我们假设我有一个Dto列表,我想遍历它们并设置一些值,然后将它们插入/更新到我的Room数据库中。因此,从ViewModel调用存储库类,在其中运行循环,然后调用dao.insertItems(list)。
import string
letters = string.ascii_lowercase
for i in range(95):
if 0 < i < 12:
well = letters[i%12]
问题是我必须在Repository类中使用哪种CourtineScope。 我是否必须使用Dispatchers.Main ..创建一个repositoryScopeScope?也许是GlobalScope ..?
答案 0 :(得分:1)
在存储库中将您的方法创建为 suspend fun
并使用 withContext(Dispatchers.IO)
例如
suspend fun updateItems() = withContext(Dispatchers.IO) {
//you work...
}
答案 1 :(得分:0)
您应该将存储库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)
}