在Android-Kotlin中,我必须使用LiveData从房间数据库读取查询吗
我使用MVVM模型开发了一个简单的购物清单应用程序 我有这些文件:在Android-Kotlin中,我必须使用LiveData从房间数据库读取查询吗,android,android-room,android-mvvm,Android,Android Room,Android Mvvm,我使用MVVM模型开发了一个简单的购物清单应用程序 我有这些文件: 数据库(2个表:购物项目和参考项目)+DAO(唯一) 存储库(唯一) ViewModel(唯一) 片段/活动 在DAO中,我定义了所有查询。当前,我所有的//自定义查询返回的LiveData类型如下: @Dao interface ShoppingDao { // Shopping Items @Insert(onConflict = OnConflictStrategy.REPLACE) susp
(2个表:购物项目和参考项目)+数据库
(唯一)DAO
(唯一)存储库
(唯一)ViewModel
/片段
活动
DAO
中,我定义了所有查询。当前,我所有的//自定义
查询返回的LiveData
类型如下:
@Dao
interface ShoppingDao {
// Shopping Items
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertShoppingItem(item: ShoppingItem)
@Delete
suspend fun deleteShoppingItem(item: ShoppingItem)
@Update
suspend fun updateShoppingItem(item: ShoppingItem)
@Query(value = "DELETE FROM shopping_items")
suspend fun deleteAllShoppingItems()
@Query(value = "SELECT * FROM shopping_items")
fun getAllShoppingItem(): LiveData<List<ShoppingItem>>
// Custom
@Query(value = "SELECT COALESCE(SUM(item_amount),0) FROM shopping_items")
fun getAllShoppingCount(): LiveData<Int>
@Query(value = "SELECT COALESCE(SUM(item_total_price), 0.0) FROM shopping_items")
fun getAllShoppingTotal(): LiveData<Float>
它返回一个作业
而不是查询
应该返回的类型。如果我可以使用除LiveData
我的想法以外的其他东西,我该如何改变这一点:
viewModelScope.launch(Dispatchers.IO){
repository.updateShoppingItem(项目)
}
希望这会有所帮助。它应该会帮助您:谢谢,但不要依赖所有问题的答案。我以前读过,但它只是说Dao不应该在之后返回LiveData?您不能在主线程中访问数据库,所以首先需要使用Dispatcher.IO,然后使用suspend before Dao函数并为其设置返回类型
fun updateShoppingItem(item: ShoppingItem) = CoroutineScope(Dispatchers.Main).launch {
repository.updateShoppingItem(item)
}