如何从另一个实时数据观察器调用实时数据观察器



我正在研究实时数据。我有两个 API,但一个 API 依赖于另一个 api。基于第一个 api 响应,我正在使用实时数据观察器调用另一个 api。我从内部观察者那里打电话,这是一种正确的方法还是任何其他选择

  mainViewModel.getListLiveData().observe(MainActivity.this, new Observer<List<Student>>() {
            @Override
            public void onChanged(@Nullable List<Student> list) {
                if(list.size() > 0){
                    mainViewModel.getStudentLiveData().observe(MainActivity.this, new Observer<Student>() {
                        @Override
                        public void onChanged(@Nullable Student student) {
                        }
                    });   
                }
            }
        });

观察学生LiveData暴露mainViewModel。在视图中模型中,使用Transformations或使用MediatorLiveData使学生实时数据随列表实时数据的变化而更改

在您的活动中:

mainViewModel.getStudentLiveData().observe(this, new Observer<Student>() {
   student -> {}
});

在您的视图中模型:

private MutableLiveData<List< Student>> studentListLiveData = new MutableLiveData(); // this will hold result of your first api call
private MutableLiveData<Student> studentLiveData = new MutableLiveData(); // this will hold result of your second api call

private void fetchData() {
    fetchStudentList(new Callback {
      result -> { 
           studentListLiveData.value = result; 
           fetchStudent(new Callback {
               result -> { studentLiveData.value = result; }
           });      
      }
    })
}
public LiveData<Student> getStudentLiveData() {
      return studentLiveData;
}

最新更新