【问题标题】:RoomDb Query Returning nullRoomDb 查询返回 null
【发布时间】: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


    【解决方案1】:

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

    1. 您的数据库查询是一个暂停方法,它将执行和“suspend”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)
    }
    

    推荐阅读:

    【讨论】:

      猜你喜欢
      • 2019-11-02
      • 2013-04-28
      • 2019-06-14
      • 2020-01-07
      • 2015-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多