Android 干货精粹

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

2022-03-18  本文已影响0人  神奇的LION

首先,封装一个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);
 
                }
            }
        });
上一篇下一篇

猜你喜欢

热点阅读