Kotlin Room+LiveData动态更改查询功能

Kotlin Room+LiveData动态更改查询功能,kotlin,android-room,android-architecture-components,android-livedata,Kotlin,Android Room,Android Architecture Components,Android Livedata,我正在制作一个应用程序来更新当前列表。实现是使用room和livedata完成的,我使用的是没有viewmodel的mvp模式。我的问题是,如果我有一个返回所选类别中所有项目的查询,并且我在livedata上已经有了一个可观察项,那么我可以用不同的查询参数更改dao函数并相应地更新列表吗。我发现最接近它的是: 但由于我对开发比较陌生,目前正在探索android中的反应模式,这已经证明是一个相当大的挑战 在演讲者中 override var itemsList: LiveData<List

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

但由于我对开发比较陌生,目前正在探索android中的反应模式,这已经证明是一个相当大的挑战

在演讲者中

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

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

在一个可变的LiveData中存储categoryId可能存在重复,然后您可以切换映射查询。@EpicPandaForce是的,tnx为输入,我知道了,它正在工作,我会在编辑中发布代码