android livedata进行顺序调用 [英] android livedata make sequential call

查看:632
本文介绍了android livedata进行顺序调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用翻新,实时数据.我的项目有一种情况,我必须进行网络呼叫的顺序.如果任何一个失败,它应该返回错误.

I am using Retrofit, Live data. There is one situation on my project, I have to make sequence of network call. if any one fails it should return error.

目前我有两个实时数据观察员来完成工作,这不是一个好的方法,所以我想知道更好的方法或示例代码来满足这种要求.

At present I have two live data observers to get the work done, which is not good approach so I wanted to know the better approach or sample code to handle such requirement.

注意:我没有使用Rxjava.

Note: I am not using Rxjava.

查看代码基本逻辑

    String id = "items/1233"; //ID which has to to be deleted
    if (isCustomizedItem) {
        viewModel.deleteEvent(id);
    } else {
        viewModel.createCustomItems();
        viewModel.deleteEvent(id);
    }

Livedata观察者

Livedata observers

    viewModel.getItemDeleted().observe(this, serverResponse -> {
        if (serverResponse.status == Status.SUCCESS) {
            Timber.i("Successfully deleted");
        }
    });

    viewModel.itemCreated().observe(this, serverResponse -> {
        if (serverResponse.status == Status.SUCCESS) {
            Timber.i("new items added");
            //Again call delete for specific item
            viewModel.deleteEvent(id);
        }
    });

Viewmodel代码

Viewmodel code

    createItems = Transformations.switchMap(eventData, (data) -> {
        if (canCreateItems(data)) {
            return AbsentLiveData.create();
        } else {
            return eventItemRepository.createItems();
        }
    });

    deleteItem = Transformations.switchMap(deleteItem, (item) -> {
        if (!isValidItem(item)) {
            return AbsentLiveData.create();
        } else {
            return eventItemRepository.deleteItem(item);
        }
    });

回购代码.

public LiveData<Resource<List<Items>>>  createItems() {
    return new NetworkBoundResource<List<Items>> (executors) {
        @NonNull
        @Override
        protected LiveData<ApiResponse<List<Items>>> createCall() {
            return services.createItems();
        }
    }.asLiveData();
}
public LiveData<Resource<EmptyResponse>>  deleteItem(String id) {
    return new NetworkBoundResource<EmptyResponse> (executors) {
        @NonNull
        @Override
        protected LiveData<ApiResponse<EmptyResponse>> createCall() {
            return services.deleteItem(id);
        }
    }.asLiveData();
}

服务界面.

@GET(Constants.API_PATH+"/createitems/")
LiveData<ApiResponse<List<Items>>> createItems();

@GET(Constants.API_PATH+"/delete/{id}")
LiveData<ApiResponse<EmptyResponse>> deleteItem(@Path("id") String id);

我想一起调用createItems和deleteItem.我该如何实现?

I want to call createItems and deleteItem together. How can i achieve this?

推荐答案

最后,我编写了解决方案.我使用Mediatorlivedata来观察viewmodel上实时数据的变化.

Finally I write the solution. I used Mediatorlivedata to observe livedata changes on viewmodel.

同时负责网络通话的方法

Method which is responsible for both network call

public LiveData<Resource<EmptyResponse>> updateEvent(RequestCustomEvent request) {
    return new UpdateItineraryRequests<EmptyResponse>(request).asLiveData();
}

和一个类,它将观察viewmodel上实时数据的变化.

and a class which will observe live data changes on viewmodel.

   private class UpdateItineraryRequests<RequestType> {
    private final MediatorLiveData<Resource<RequestType>> result = new MediatorLiveData<>();

    UpdateItineraryRequests(RequestCustomEvent request) {
        startExecution(request);
    }

    void startExecution(RequestCustomEvent request) {
        //First check the its custom or not if its custom then directly change.
        if (request.isCustom()) {
            LiveData<Resource<EmptyResponse>> observable = repo.deleteItem(request.getEventID());
            result.addSource(observable, response -> {
                result.removeSource(observable);
                if (response.status == Status.SUCCESS) {
                    result.setValue(Resource.success(null));
                } else {
                    result.setValue(Resource.error("unable to delete", null));
                }

            });
        } else {
            LiveData<Resource<List<Items>>> itemsObservable = repo.createItems(request.getDataToChange());
            result.addSource(itemsObservable, response -> {
                result.removeSource(itemsObservable);
                LiveData<Resource<EmptyResponse>> observable = repo.deleteItem(request.getEventID());
                result.addSource(observable, response -> {
                    result.removeSource(observable);
                    if (response.status == Status.SUCCESS) {
                        //Do rest of network calls
                    }

                }
            });
        }

    }

    LiveData<Resource<RequestType>> asLiveData() {
        return result;
    }

}

这篇关于android livedata进行顺序调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆