kotlin - Room + LiveData 动态变更查询功能

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

我正在制作一个应该更新当前列表的应用程序。实现是使用 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/

相关文章:

android - 在导航组件中使用带有安全参数的 parcelable

android - 如何模拟 Kotlin 中的对象?

Android Room library - 选择嵌入式实体的所有字段

java - 是否可以将同一个对象保存到两个不同的表房间?

java - 我如何从 Presenter (MVP) 初始化 Room 数据库

Android Paging3 insertSeparators 无法按预期工作

java - 多 Activity 中用 EventBus 替换 LiveData

kotlin - 如何将可变参数传递给 Kotlin 中的可变参数函数或构造函数?

android - 将数据从 Viewmodel 设置为 Activity android kotlin

kotlin - 使用动态属性名称将属性分配给 javascript 对象