更新:::

我已经更新了问题,以包括还需要演示的其他LiveData:
 因此,我们有userLD,我们需要其值来获取GoalWeeklyLD,并且我们需要GoalWeeklyLD值来获取其余4个LiveData值,因为它们来自使用查询中使用GoalWeekly.dateproperties的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());
}}

最佳答案

值得庆幸的是,谷歌很聪明,创建了一个组件,可让您将可变数量的LiveData组合到单个LiveData中,并且仅在您选择这样做时才发出事件!

这称为MediatorLiveData。

但是,在您的情况下,您只需要将1个LiveData(userLD)传递给另一个LiveData 1个,则每次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()));

}

关于java - Java Android LiveData调用依赖于其他LiveData的Room查询,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55167731/

10-12 06:23