ViewModel - change parameter of method while observing LiveData at runtime?

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:

public class CarsViewModel extends ViewModel {
    private CarRepository mCarRepository;
    private LiveData<List<Car>> mAllCars;
    private LiveData<List<Car>> mCarsFilteredByColor;
    private MutableLiveData<String> filterColor = new MutableLiveData<String>();
    
    public CarsViewModel (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 search
    void setFilter(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.

Tags:

Android

Mvvm