[英]RoomDb Query Returning null
I am querying my room database to check if an item exists, however the query always returns null even though the item is already in the DB.我正在查询我的房间数据库以检查某个项目是否存在,但是即使该项目已在数据库中,该查询也始终返回 null。 I am using coroutines
我正在使用协程
This is my query这是我的查询
@Query("SELECT EXISTS(SELECT * FROM cart_item WHERE productId = :productId)")
suspend fun getItemCount(productId: Int): Int?
The function in my repository我的存储库中的函数
suspend fun getCartItemCount(productId: Int): Int? {
return coroutineScope{
cartItemDao.getItemCount(productId)
}
}
In my view model在我的视图模型中
fun getCartItemCount(productId: Int): MutableLiveData<Int>? {
var itemCount: MutableLiveData<Int>? = MutableLiveData()
launch {
itemCount!!.value = repository.getCartItemCount(productId)
}
return itemCount
}
And this is how i implement it in my Fragment这就是我在 Fragment 中实现它的方式
fun getCartItemCount(productId: Int){
var itemCount: Int? = null
mainViewModel!!.getCartItemCount(productId)!!.observe(viewLifecycleOwner, Observer {
itemCount = it
})
Log.d("ITEMCOUNT ----> ", " $itemCount")
}
I think you are missing some fundamentals on how to use coroutines.我认为您缺少有关如何使用协程的一些基础知识。
itemCount
while still null.itemCount
。 The trigger never did, and even if it does, it won't execute your log statement. Your view model uses LiveData
to post changes, then we do you need to return a value on your method?您的视图模型使用
LiveData
来发布更改,那么您需要在您的方法上返回一个值吗?
Suggested Changes建议的更改
Repository存储库
// repository
suspend fun getCartItemCount(productId: Int): Int? {
return cartItemDao.getItemCount(productId)
}
View Model查看模型
var itemCount: MutableLiveData<Int> = MutableLiveData()
// maybe rename method as it's not a getter anymore
fun getCartItemCount(productId: Int) {
viewModelScope {
itemCount.value = repository.getCartItemCount(productId)
}
}
In your fragment在你的片段中
fun getCartItemCount(productId: Int){
mainViewModel?.observe(viewLifecycleOwner, Observer {
itemCount = it
// this will be triggered every time the "LiveData.value" changes
// this could return null if the live data value is not set.
Log.d("ITEMCOUNT", "$it")
})
mainViewModel?.getCartItemCount(productId)
}
Suggested Reading:推荐阅读:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.