【发布时间】:2020-05-07 23:58:39
【问题描述】:
我使用 MVVM 模型开发了一个简单的购物清单 App。
我有这些文件:
-
Database(2 表:购物项目和参考项目)+DAO(唯一) -
Repository(唯一) -
ViewModel(唯一) -
Fragment/Activity
在DAO 中,我定义了所有查询。目前,我所有的//Custom 查询都返回一个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>
然后在存储库中,它们都没有使用suspend fun 来调用。因此,在 ViewModel 中,它们也不会使用 suspend fun 来调用。
我想使用getAllShoppingCount(),例如不使用LiveData 和Observer。
有可能吗?
这是最佳实践吗?
如果没有 LiveData,我将不得不使用 suspend fun 来完成我的 Query,但是当我使用时:
fun updateShoppingItem(item: ShoppingItem) = CoroutineScope(Dispatchers.Main).launch {
repository.updateShoppingItem(item)
}
它返回 Job 而不是 Query 应该返回的类型。如果我可以使用 LiveData 以外的其他内容,我该如何更改。
【问题讨论】:
-
谢谢,但不依赖对所有问题的回答。我之前读过,但它只是说 Dao 不应该在那之后返回 LiveData ?
-
主线程无法访问数据库,所以首先需要使用Dispatcher.IO,然后在dao函数之前使用suspend,并为其设置返回类型
标签: android android-room android-mvvm