gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:33:46 28 4
gpt4 key购买 nike

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

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

最佳答案

如前所述in this answer ,您的解决方案是 Transformation.switchMap

来自 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 onchanges of trigger LiveData, applies the given function to new valueof trigger LiveData and sets resulting LiveData as a "backing"LiveData to swLiveData. "Backing" LiveData means, that all eventsemitted by it will retransmitted by 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); }
}

因此,当您从 View 中调用 setFilter 方法时,更改 filterColor LiveData 将触发 Transformation.switchMap,它将调用 mRepository.getCarsByColor(c)) 并且然后使用查询结果更新 mCarsFilteredByColor LiveData。因此,如果您在 View 中观察此列表并设置不同的颜色,则观察者会收到新数据。

关于android - ViewModel - 在运行时观察 LiveData 时更改方法的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53346754/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com