UPDATE :::
我已更新了问题,以包括还需要演示的其他LiveData: 因此,我们有userLD,我们需要它的值来获取GoalWeeklyLD,并且我们需要goalWeeklyLD值来获取剩余的4个LiveData值,因为它们来自在查询中使用goalWeekly.date属性的Room查询。
:::::
我遇到了一个问题,其中有一个片段必须填充LiveData,该片段使用依赖于另一个LiveData值的查询。 依赖其他结果时,如何使实时数据正常工作?
如果不使用Transitions.map(),则视图模型将引发错误,因为其他实时数据的值仍为null。 在视图模型中使用Transitions.map()时,活动观察者将引发错误,因为LiveData仍然为null。
我可以通过使用一个可怕的大嵌套查询来返回我需要的所有自定义DTO中的内容,以此来欺骗自己。但是我宁愿了解这里发生了什么以及如何正确处理这种情况。
希望一些代码可以使之清晰
活动:
public class SomeFragment extends Fragment {
public static SomeFragment newInstance() {
return new SomeFragment();
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
someViewModel = ViewModelProviders.of(this).get(SomeViewModel.class);
//getting user details from previous activity
Intent intent = getActivity().getIntent();
if (intent != null){
if (intent.hasExtra(USER_ID)){
user = new User(intent.getStringExtra(USERNAME));
user.setId(intent.getLongExtra(USER_ID,0));
someViewModel.setUserLD(user);
}
}
someViewModel.getUserLD().observe(this, new Observer<User>() {
@Override
public void onChanged(@Nullable User userVal) {
user = userVal;
}
});
someViewModel.getGoalWeeklyLD().observe(this, new Observer<User>() {
@Override
public void onChanged(@Nullable User userVal) {
user = userVal;
}
});
//the below Observer calls throw an error because LiveData is null. makes sense.
//but how can i say "don't try and observe these until the transition.map has ran (because then it wont be null after if my understanding is right)" or something to that effect
someViewModel.getFirstLD(user.getId()).observe(this, new Observer<XObject>() {
@Override
public void onChanged(@Nullable Grades avgSportGradeVal) {
//Update UI
}
});
someViewModel.getSecondLD(user.getId()).observe(this, new Observer<XObject>() {
@Override
public void onChanged(@Nullable Grades avgBoulderGradeVal) {
// Update UI
}
});
someViewModel.getThriLD(user.getId()).observe(this, new Observer<XObject>() {
@Override
public void onChanged(@Nullable Grades avgBoulderGradeVal) {
// Update UI
}
});
someViewModel.getFourthLD(user.getId()).observe(this, new Observer<XObject>() {
@Override
public void onChanged(@Nullable Grades avgBoulderGradeVal) {
// Update UI
}
});
}}
视图模型:
public class SomeViewModel extends AndroidViewModel {
DaoRepository daoRepository;
MutableLiveData<User> userLD;
LiveData<XObject> firstLD;
LiveData<XObject> secondLD;
LiveData<XObject> thirdLD;
LiveData<XObject> fourthLD;
public MutableLiveData<User> getUserLD() {
return userLD;
}
public void setUserLD(User user){
userLD.setValue(user);
}
public LiveData<XObject> getFirstLD(long userId) {
return goalWeeklyLD;
}
public LiveData<XObject> getSecondLD(long userId) {
return goalWeeklyLD;
}
public LiveData<XObject> getThirdLD(long userId) {
return goalWeeklyLD;
}
public LiveData<XObject> getForthLD(long userId) {
return goalWeeklyLD;
}
public SomeViewModel(@NonNull Application application) {
super(application);
daoRepository = new DaoRepository(application);
userLD = new MutableLiveData<>();
//so the first LiveData waits for the user to be populated before getting its LiveData becasue we need the userId for our Room query to run
firstLD = Transformations.map(userLD, user -> daoRepository.getMostRecentGoalWeekly(user.getId()).getValue());
//the remaining live data uses values from the first...
setupOtherTransformMaps(userLD.getValue())
}
public void setupOtherTransformMaps(long userId) {
//the secondLD, thirdLD and fourthLD all depends on values from the first (in runs a query that uses its dateExpired)
secondLD = Transformations.map(firstLD, first ->
daoRepository.getAvgGradeRouteInPeriod(userId, first.getDateCreated(),first.getDateExpires()).getValue());
thirdLD = Transformations.map(firstLD, first ->
daoRepository.getAvgGradeRouteInPeriod(userId, first.getDateCreated(),first.getDateExpires()).getValue());
fourthLD = Transformations.map(firstLD, first ->
daoRepository.getAvgGradeRouteInPeriod(userId, first.getDateCreated(),first.getDateExpires()).getValue());
}}
答案 0 :(得分:1)
非常感谢Google的聪明才智,并创建了一个组件,该组件可让您将可变数量的LiveData组合到单个LiveData中,并且仅在您选择这样做时才发出事件!
这称为MediatorLiveData。
尽管如此,您只需要将1个LiveData(userLD
)传递到另一个LiveData中,每当userLd
具有新值时,该LiveData就会发出。
因此,您可以使用精确地执行此操作的预定义MediatorLiveData,特别是Transformations.switchMap
。
firstLD = Transformations.switchMap(userLD, user -> daoRepository.getMostRecentGoalWeekly(user.getId()));
编辑:是的,您似乎需要将这些LiveData彼此分开公开,但是它们都取决于要执行的第一个查询。
因此您需要将Transformations.map { ...getValue()
替换为Transformations.switchMap
,您会很方便。
public SomeViewModel(@NonNull Application application) {
super(application);
CustomApplication app = (CustomApplication) application;
daoRepository = app.daoRepository();
userLD = new MutableLiveData<>();
firstLD = Transformations.switchMap(userLD, user -> daoRepository.getMostRecentGoalWeekly(user.getId()));
secondLD = Transformations.switchMap(firstLD, first ->
daoRepository.getAvgGradeRouteInPeriod(userId, first.getDateCreated(),first.getDateExpires()));
thirdLD = Transformations.switchMap(firstLD, first ->
daoRepository.getAvgGradeRouteInPeriod(userId, first.getDateCreated(),first.getDateExpires()));
fourthLD = Transformations.switchMap(firstLD, first ->
daoRepository.getAvgGradeRouteInPeriod(userId, first.getDateCreated(),first.getDateExpires()));
}