我要:
将数据提取到我的ViewModel。
将其拆分为LiveData对象。
用它做一些事情,然后再将其传递给我的视图。
某些用户选项相互依赖。例如,更改 mGender 必须更改 mAge 所以,这就是我要做的
DAO
@Query("SELECT * FROM users WHERE _id = :id")
LiveData<User> getUserById(int id);
ViewModel
private MediatorLiveData<Integer> mUnitSystem = new MediatorLiveData<>();
private MediatorLiveData<Integer> mAge = new MediatorLiveData<>();
private MediatorLiveData<Integer> mGender = new MediatorLiveData<>();
private MediatorLiveData<Double> mHeight = new MediatorLiveData<>();
public UserSettingsViewModel(@NonNull Application application) {
super(application);
mData = Injector.getDataReporitory(application);
MediatorLiveData<User> userMediatorLiveData = new MediatorLiveData<>();
userMediatorLiveData.addSource(mData.getUser(1), new Observer<User>() {
@Override
public void onChanged(@Nullable User user) {
mUnitSystem.postValue(user.getUnitSystem());
mAge.postValue(user.getAge());
mGender.postValue(user.getGender());
mHeight.postValue(user.getHeight());
}
});
userMediatorLiveData.observeForever(new Observer<User>() {
@Override
public void onChanged(@Nullable User user) {
}
});
mGender.addSource(mUnitSystem, new Observer<Integer>() {
@Override
public void onChanged(@Nullable Integer integer) {
mAge.postValue(integer + 10);
}
});
}
public LiveData<Integer> getGender() {
return mGender;
}
public LiveData<Integer> getAge() {
return mAge;
}
public LiveData<Integer> getUnitSystem() {
return mUnitSystem;
}
// setter to them
因此,它的工作原理。但是,我真的对ViewModel中的observeForever()感到困惑。我知道Google不建议这样做。
我想要更干净的方法。
提前谢谢!