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

2024-01-12

我正在尝试弄清楚 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);
            }
        });

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

现在我的问题 - 有没有办法改变color里面的变量getAllCars方法(例如通过按钮单击)并影响观察者返回新列表?如果我只是改变颜色变量,什么也不会发生。


就像声明的那样在这个答案中 https://stackoverflow.com/a/49669526/10648865,你的解决方案是Transformation.switchMap

From Android 开发者网站: https://developer.android.com/reference/android/arch/lifecycle/Transformations

LiveData switchMap (LiveData 触发器, Function> func)

创建一个 LiveData,我们将其命名为 swLiveData,它遵循下一个流程:它对 触发 LiveData 的更改,将给定函数应用于新值 触发 LiveData 并将生成的 LiveData 设置为“支持” LiveData 到 swLiveData。 “支持”LiveData 意味着所有事件 它发出的数据将由 swLiveData 重新传输。

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

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); }
}

所以当你调用setFilter从你的角度来看,更改过滤器 Color LiveData 将触发 Transformation.switchMap,它将调用mRepository.getCarsByColor(c))然后使用查询结果更新 mCarsFilteredByColor LiveData。因此,如果您在视图中观察此列表并设置不同的颜色,则观察者会收到新数据。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐