Room + LiveData动态变化查询功能

Room + LiveData change query function dynamically

我正在制作一个应该更新当前列表的应用程序。实现是使用 room 和 livedata 完成的,我使用的是没有 viewmodel 的 mvp 模式。我的问题是,如果我有一个查询 returns 所选类别中的所有项目并且我在实时数据上已经有一个可观察对象,我可以使用不同的查询参数更改 dao 函数并相应地更新列表。我发现最接近它的是:

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

在主持人中

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

在 mainAcivity

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

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

编辑(解决方案)

解决方案是 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
    }
}