ViewModel-在运行时观察LiveData时更改方法的参数?

vre*_*bek 4 android mvvm

我试图弄清楚MVVM(对我来说这是很新的东西),并且弄清楚了如何使用Room和ViewModel观察LiveData。现在我面临一个问题。

我有一个需要参数的Room查询,这就是我开始在MainActivity的onCreate中观察LiveData的方式。

    String color = "red";
    myViewModel.getAllCars(color).observe(this, new Observer<List<Car>>() {
            @Override
            public void onChanged(@Nullable List<Car> cars) {
                adapter.setCars(cars);
            }
        });
Run Code Online (Sandbox Code Playgroud)

通过使用此代码,我收到了“红色”汽车的列表,并用该列表填充RecyclerView。

现在我的问题-是否有办法更改方法color内部的变量getAllCars(例如通过单击按钮)并影响观察者返回新的List?如果我只是更改color变量,则什么也不会发生。

dgl*_*ano 6

该答案所述,您的解决方案是Transformation.switchMap

Android for Developers网站:

LiveData <Y> switchMap(LiveData <X>触发器,Function <X,LiveData <Y >> func)

创建一个LiveData,将其命名为swLiveData,它遵循下一个流程:它对触发器LiveData的更改做出反应,将给定函数应用于触发器LiveData的新值,并将生成的LiveData设置为swLiveData的“后备” LiveData。“备份” LiveData表示,它发出的所有事件都将由swLiveData重传。

在您的情况下,它看起来像这样:

public class CarsViewModel extends ViewModel {
    private CarRepository mRepository;
    private LiveData<List<Car>> mAllCars;
    private LiveData<List<Car>> mCarsFilteredByColor;
    private MutableLiveData<String> filterColor = new MutableLiveData<String>();

    public CarsViewModel (CarRepository carRepository) {
        super(application);
        mRepository = carRepository;
        mAllCars = mRepository.getAllCars();
        mCarsFilteredByColor = Transformations.switchMap(filterColor,
                                                c -> mRepository.getCarsByColor(c));
    }

    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); }
    LiveData<List<Car>>> getAllCars() { return mAllCars; }
}
Run Code Online (Sandbox Code Playgroud)

因此,当您setFilter从视图中调用该方法时,更改filterColor LiveData将触发Transformation.switchMap,后者将调用mCarsFilteredByColor LiveData mRepository.getCarsByColor(c)),然后使用查询结果进行更新。因此,如果您在视图中观察此列表并设置了其他颜色,则观察者将接收到新数据。

让我知道它是否有效。

  • 你的代码很有帮助。但是该行有一个问题:`private LiveData&lt;String&gt; filterColor = new MutableLiveData&lt;String&gt;();`而不是使用`private MutableLiveData&lt;String&gt; filterColor = new MutableLiveData&lt;String&gt;();`因为**LiveData的** `setValue()` 具有受保护的访问权限,而 **MutableLiveData 的** `setValue()` 具有公共访问权限。 (2认同)