简体   繁体   English

如何从另一个liveData观察者调用liveData观察者

[英]How to call liveData observer from another liveData observer

I am working on livedata. 我正在研究livingata。 I have two apis but one api is dependent on another api. 我有两个api,但一个api依赖于另一个api。 Based on first api response i am calling another api using livedata observer. 基于第一个api响应,我使用livingata观察者调用另一个api。 I am calling from inside observer is this a right approach or any other alternative 我从内部观察者那里呼唤这是一种正确的方法或任何其他选择

  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) {

                        }
                    });   
                }

            }
        });

Observe on the student LiveData exposed by the mainViewModel . 观察LiveData公开的学生mainViewModel In the viewmodel make student live data change with change in List LiveData using Transformations or using a MediatorLiveData 在视图模型中,通过使用Transformations或使用MediatorLiveData更改List LiveData中的学生实时数据

In your activity: 在您的活动中:

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

In your viewmodel: 在您的viewmodel中:

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM