我正在制作一个应该更新当前列表的应用程序。实现是使用 room 和 livedata 完成的,我使用的是没有 viewmodel 的 mvp 模式。我的问题是,如果我有一个查询返回所选类别中的所有项目,并且我已经在 livedata 上有一个可观察的对象,我是否可以使用不同的查询参数更改 dao 函数并相应地更新列表。我发现的最接近它的是:
Android Room LiveData select query parameters
但由于我对开发相对较新,并且目前正在探索 android 中的响应式(Reactive)范例,这已被证明是一个相当大的挑战。
在主持人
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
}
}
这只是对同一类别的查询,但通过不同的处理,一切皆有可能。
最佳答案
编辑(解决方案)
解决方案是 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
}
}
关于kotlin - Room + LiveData 动态变更查询功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54521350/