美文网首页Android 干货精粹
Android中对LiveData的多个请求结果进行合并

Android中对LiveData的多个请求结果进行合并

作者: 神奇的LION | 来源:发表于2022-03-18 17:41 被阅读0次

    首先,封装一个LiveData结果的合并类。通过扩展MediatorLiveData来实现。

    public class MyLiveData extends MediatorLiveData<Boolean> {
     
        public ApiResult<List<Model1>> model1ApiResult;
        public ApiResult<List<Model2>> model2ApiResult;
        public ApiResult<List<Model3>> model3ApiResult;
     
        public int finishRequestCount;
     
        
        //添加请求联系人数据的observer到source
        public void addModel1ListSource(LiveData<ApiResult<List<Model1>>> source) {
            addSource(source, (Observer<ApiResult<List<Model1>>>) apiResult -> {
                model1ApiResult = apiResult; //暂存Model1列表结果
                finishRequestCount++;
                postValue(finishRequestCount == 3); //在三个请求都完成时,通知结果完成
            });
        }
     
        public void addModel2ListSource(LiveData<ApiResult<List<Model2>>> source) {
            addSource(source, (Observer<ApiResult<List<Model2>>>) apiResult -> {
                model2ApiResult = apiResult;
                finishRequestCount++;
                postValue(finishRequestCount == 3);
            });
        }
     
        public void addModel3ListSource(LiveData<ApiResult<List<Model3>>> source) {
            addSource(source, (Observer<ApiResult<List<Model3>>>) apiResult -> {
                model3ApiResult = apiResult;
                finishRequestCount++;
                postValue(finishRequestCount == 3);
            });
        }
    }
    

    然后,结合使用LiveData并合并之,统一处理结果。

            ApiService apiService = NetworkFactory.getInstance().getApiService();
     
            Map<String, Object> params = new HashMap<>();
           
            LiveData<ApiResult<List<Model1>>> source1 = apiService.reqModel1List(params);
     
            LiveData<ApiResult<List<Model2>>> source2 = apiService.reqModel2List(params);
     
            LiveData<ApiResult<List<Model3>>> source3 = apiService.reqModel3List(params);
     
           
            MyLiveData liveDataMerger = new MyLiveData();
            liveDataMerger.addModel1ListSource(source1);
            liveDataMerger.addModel2ListSource(source2);
            liveDataMerger.addModel3ListSource(source3);
     
            liveDataMerger.observe(this, new Observer<Boolean>() {
                @Override
                public void onChanged(Boolean finish) {
                    if (finish) { //三个请求都完成时,统一处理相关数据
                        setModel1List(liveDataMerger.model1ApiResult);
                        setModel2List(liveDataMerger.model2ApiResult);
                        setModel3List(liveDataMerger.model3ApiResult);
     
                    }
                }
            });
    

    相关文章

      网友评论

        本文标题:Android中对LiveData的多个请求结果进行合并

        本文链接:https://www.haomeiwen.com/subject/xqqwdrtx.html