11

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?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Bashir Fardoush
  • 184
  • 1
  • 10
  • 1
    when changing your `busCategory` you need to call that `viewmodel` method again, to fetch new data with new `busCategory`. – Muhammad Awais Oct 09 '19 at 11:18
  • @MuhammadAwais then it observes for both bus category, in onChanged method it also gets value for previous busCategory – Bashir Fardoush Oct 09 '19 at 11:26
  • 1
    For the second method you don't need to call `observe` method. As it is already observing in your view. Once the data is changed your `onChanged()` method will be called with new data. – Muhammad Awais Oct 09 '19 at 11:27
  • I have the same problem. Need to change the query param. After days of tests and searches, I did not come with a clear answer. Hope someone will illuminate us. – Dan Alboteanu Oct 30 '19 at 19:36

2 Answers2

21

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)
Dan Alboteanu
  • 9,404
  • 1
  • 52
  • 40
Zulqarnain
  • 611
  • 7
  • 18
0

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

ayoola adedeji
  • 119
  • 1
  • 8
  • i can remove observer and set new observer and call for new livedata. But how to stop current live data instance ? so that room will not emit data for current livedata instance. – Bashir Fardoush Oct 09 '19 at 11:32
  • Assuming you only want one response you can unsubscribe to it after getting that response? – ayoola adedeji Oct 10 '19 at 12:03