问题描述
我想通过多个数据库查询向数据库添加值。 这些操作不需要 UI 的东西,所以我认为还有另一种方法可以实现这一点。我知道 有事件通道,我可以在每个房间查询后发送在活动/片段中收集的密封类, 但我认为应该有更简单的方法。
我做了一个草稿(只是一段理论上的代码): 在 viewmodel 中,我有一个这样的函数,其中 5 个 DB 查询将结果相互连接:
fun add(item: Something) = viewmodelScope.launch {
val itemsNumber = itemDao.getItems()
val list = mutablelistof()
if (itemsNumber == 0){
val newItem = Item()
val insertedId = itemDao.insert(newItem)
val other = Other(id = insertedId,title = "Sha-la-la")
val insertedOtherId = otherDao.insert(other)
list = itemDao.getItems()
if (list.size > 0){
val anotherItemList = mutablelistof(Another(oid = insertedOtherId),Another(oid = insertedOtherId) )
val insId = anotherDao.insertAll(anotherItemList)
}
}
项目 DAO:
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(item: Item): Long
@Transaction
@Query("SELECT COUNT(*) FROM items WHERE id = :itemId ")
suspend fun getItems(itemId: Long): Int
其他道:
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(other: Other): Long
另一个道:
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertAll(item: List<Another>): List<Long>
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)