Viewmodel - Change Parameter Of Method While Observing Livedata At Runtime?
Solution 1:
As stated in this answer, your solution is Transformation.switchMap
From Android for Developers website:
LiveData< Y > switchMap (LiveData< X > trigger, Function< X, LiveData< Y >> func)
Creates a LiveData, let's name it swLiveData, which follows next flow: it reacts on changes of trigger LiveData, applies the given function to new value of trigger LiveData and sets resulting LiveData as a "backing" LiveData to swLiveData. "Backing" LiveData means, that all events emitted by it will retransmitted by swLiveData.
In your situation, it would look something like this:
publicclassCarsViewModelextendsViewModel {
privateCarRepository mCarRepository;
privateLiveData<List<Car>> mAllCars;
privateLiveData<List<Car>> mCarsFilteredByColor;
privateMutableLiveData<String> filterColor = newMutableLiveData<String>();
publicCarsViewModel (CarRepository carRepository) {
super(application);
mCarRepository= carRepository;
mAllCars = mCarRepository.getAllCars();
mCarsFilteredByColor = Transformations.switchMap(
filterColor,
color -> mCarRepository.getCarsByColor(color)
);
}
LiveData<List<Car>>> getAllCars() { return mAllCars; }
LiveData<List<Car>> getCarsFilteredByColor() { return mCarsFilteredByColor; }
// When you call this function to set a different color, it triggers the new searchvoidsetFilter(String color) { filterColor.setValue(color); }
}
So when you call the setFilter
method from your view, changing the filterColor LiveData will triger the Transformation.switchMap, which will call mRepository.getCarsByColor(c))
and then update with the query's result the mCarsFilteredByColor LiveData. Hence, if you are observing this list in your view and you set a different color, the observer receive the new data.
Solution 2:
Other than @dglozano answer, one easy way to do this is to observe the color
instead of observing the list
. And on valueChange
of color
, fetch new list.
Example:
In ViewModel
class do this
MutableLiveData<String> myColor = newMutableLiveData<String>();
In Activity
do this:
button.setOnClickListener(newOnClickListener() {
publicvoidonClick(View v)
{
myViewModel.myColor.setValue("newColor");
} });
myViewModel.myColor.observe(this, newObserver<String>() {
@OverridepublicvoidonChanged(@NullableString newValue) {
// do this on dedicated threadList<Car> updateList = myViewModel.getCarsByColor(newValue)
// update the RecyclerView
}
});
Note: 1.The getCarsByColor()
need not to be wrapped as LiveData
. The method in Dao
can return List<Cars>
instead of LiveData<List<Cars>>
.
2.Don't run the db queries on main thread, and do call the notifyDataSetChanged
to refresh the RecyclerView.
Post a Comment for "Viewmodel - Change Parameter Of Method While Observing Livedata At Runtime?"