【发布时间】:2020-02-23 08:45:26
【问题描述】:
我正在查询我的房间数据库以检查项目是否存在,但是即使项目已经在数据库中,查询也总是返回 null。我正在使用协程
这是我的查询
@Query("SELECT EXISTS(SELECT * FROM cart_item WHERE productId = :productId)")
suspend fun getItemCount(productId: Int): Int?
我的仓库中的函数
suspend fun getCartItemCount(productId: Int): Int? {
return coroutineScope{
cartItemDao.getItemCount(productId)
}
}
在我的视图模型中
fun getCartItemCount(productId: Int): MutableLiveData<Int>? {
var itemCount: MutableLiveData<Int>? = MutableLiveData()
launch {
itemCount!!.value = repository.getCartItemCount(productId)
}
return itemCount
}
这就是我在 Fragment 中实现它的方式
fun getCartItemCount(productId: Int){
var itemCount: Int? = null
mainViewModel!!.getCartItemCount(productId)!!.observe(viewLifecycleOwner, Observer {
itemCount = it
})
Log.d("ITEMCOUNT ----> ", " $itemCount")
}
【问题讨论】:
标签: android kotlin android-room kotlin-coroutines