Mis*_*iso 3 kotlin android-room android-livedata android-architecture-components
我正在制作一个应该更新当前列表的应用程序。实现是使用 room 和 livedata 完成的,我使用的是没有 viewmodel 的 mvp 模式。我的问题是,如果我有一个查询返回所选类别中的所有项目,并且我在 livedata 上已经有一个可观察对象,我是否可以使用不同的查询参数更改 dao 函数并相应地更新列表。我发现的最接近它的是: Android Room LiveData select query parameters
但由于我对开发相对较新,并且目前正在探索 android 中的反应式范例,这已被证明是一个相当大的挑战。
在主持人
override var itemsList: LiveData<List<Item>?> =
itemDao.getItemsForCategory(1)
Run Code Online (Sandbox Code Playgroud)
在主要活动中
presenter.itemsList.observe(this, Observer {
if (it != null) {
itemAdapter.setTodoItems(it)
itemListHolder.adapter =itemAdapter
}
})
Run Code Online (Sandbox Code Playgroud)
在道
@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>?>
Run Code Online (Sandbox Code Playgroud)
编辑(解决方案)
解决方案是 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
}
}
Run Code Online (Sandbox Code Playgroud)
这只是对同一类别的查询,但通过不同的处理,一切皆有可能。
编辑(解决方案)
解决方案是 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
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1718 次 |
最近记录: |