【问题标题】:Room + LiveData change query function dynamicallyRoom + LiveData 动态变化查询功能
【发布时间】:2019-02-04 17:30:39
【问题描述】:

我正在制作一个应该更新当前列表的应用。实现是使用房间和实时数据完成的,我使用的是没有视图模型的 mvp 模式。我的问题是,如果我有一个返回所选类别中所有项目的查询,并且我在 livedata 上已经有一个 observable,我可以使用不同的查询参数更改 dao 函数并相应地更新列表。我发现的最接近它的是: Android Room LiveData select query parameters

但由于我对开发比较陌生,并且目前正在探索 android 中的响应式范例,这已被证明是一个相当大的挑战。

在演示者中

override var itemsList: LiveData<List<Item>?> = 
itemDao.getItemsForCategory(1)

在主活动中

presenter.itemsList.observe(this, Observer {
    if (it != null) {
        itemAdapter.setTodoItems(it)
        itemListHolder.adapter =itemAdapter
    }
})

在道

@Query("SELECT * FROM Item")
fun getItemsFromDatabase(): LiveData<List<Item>?>

@Query("SELECT * FROM Item WHERE category_id == :category_id ORDER BY 
creationTime ASC")
fun getItemsForCategory(category_id: Long): LiveData<List<Item>?>

编辑(解决方案)

解决方案是 mutableLiveData,其中值会更改查询参数:

override var itemsList: LiveData<List<IItem>?> = Transformations.switchMap(mutableLiveData) {
    itemDao.getItemsForCategory(mutableLiveData.value!!.toLong())
}

override fun onItemsCalled(categoryId: Long) {
    when (mutableLiveData.value) {
        1 -> mutableLiveData.value = 2
        2 -> mutableLiveData.value = 3
        3 -> mutableLiveData.value = 4
        4 -> mutableLiveData.value = 1
    }
}

这只是对同一类别的查询,但处理方式不同,一切皆有可能。

【问题讨论】:

  • 将 categoryId 存储在 MutableLiveData 中,然后您可以根据它 switchMap 查询。
  • @EpicPandaForce 是的,输入 tnx,我知道了,它现在可以工作了,我在编辑中发布代码

标签: kotlin android-room android-architecture-components android-livedata


【解决方案1】:

编辑(解决方案)

解决方案是 mutableLiveData,其中值会更改查询参数:

override var itemsList: LiveData<List<IItem>?> = Transformations.switchMap(mutableLiveData) {
itemDao.getItemsForCategory(mutableLiveData.value!!.toLong())
}

override fun onItemsCalled(categoryId: Long) {
    when (mutableLiveData.value) {
        1 -> mutableLiveData.value = 2
        2 -> mutableLiveData.value = 3
        3 -> mutableLiveData.value = 4
        4 -> mutableLiveData.value = 1
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多