how to change LiveData observable query parameter with room database in android?

给你一囗甜甜゛ 提交于 2020-05-27 05:41:28

问题


I am using live data with room database and my activity observes live data provided from room database.

@Query("SELECT * FROM BUS WHERE BUS_CATEGORY = :busCategory")
LiveData<List<Bus>> getLiveBuses( String busCategory);

ViewModels gets LiveData via Dao(Data Access Object) and activity observes this live data.

Now it works fine. But when busCategory changes i can't modify this live data to get buses for newly selected busCategory.

So how can i observe this same liveData where query parameters is changeable?


回答1:


I suggest you to to use viewModel. I did the query and observe changes using MutableLiveData. First step

val mutableBusCategory: MutableLiveData<String> = MutableLiveData()

Setter for mutablelivedata

fun searchByCategory(param: String) {
    mutableBusCategory.value = param
}

observable to observe the change

val busObservable: LiveData<Bus> = Transformations.switchMap(mutableBusCategory) { param->
    repository.getLiveBuses(param)
}

and final step to observe the live data

 busObservable.observe(this, Observer {
        //your logic for list})

and to trigger mutablelivedata

searchByCategory(//categoryName)



回答2:


I don't think this is a reasonable expectation. It would make more sense to fire off a new query and subscribe to that.



来源:https://stackoverflow.com/questions/58302768/how-to-change-livedata-observable-query-parameter-with-room-database-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!