繁体   English   中英

RoomDb 查询返回 null

[英]RoomDb Query Returning null

我正在查询我的房间数据库以检查某个项目是否存在,但是即使该项目已在数据库中,该查询也始终返回 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")
    }

我认为您缺少有关如何使用协程的一些基础知识。

  1. 您的数据库查询是一个挂起方法,它将执行并“挂起”tge 执行直到它返回。
  2. 由于您的存储库功能仍然是suspend ,您可以根据要在哪个范围内运行的用户来使用它。
  3. 然后我们有 LiveData 问题,您在仍然为空时记录itemCount 触发器从未执行过,即使执行了,它也不会执行您的日志语句。
  4. 您的视图模型使用LiveData来发布更改,那么您需要在您的方法上返回一个值吗?

    • 实际问题在于同步等待结果,而事实并非如此。

建议的更改

存储库

// repository
suspend fun getCartItemCount(productId: Int): Int? {
   return cartItemDao.getItemCount(productId)

}

查看模型

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)
  }
}

在你的片段中

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)
}

推荐阅读:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM