Retrofit+RxBus事件流顶层封装Core库

2019-10-04  本文已影响0人  Laughing_G

一、如何优雅的使用Retrofit网络请求库?

众所周知,Retrofit+OkHttp给我们开发者的网络请求提供了福音,但是使用者调用起来还是有些许的麻烦,接下来第一步该如何简化客户端的调用逻辑呢?

1.设计模式-建造者设计模式通过链式调度的方式,来生成客户端网络请求:

public class RestClient {

    private final HashMap<String, Object> PARAMS;
    private final String URL;
    private final IRequest REQUEST;
    private final ISuccess SUCCESS;
    private final IFailure FAILURE;
    private final IError ERROR;
    private final RequestBody BODY;
    //上传或下载
    private final File FILE;
    private final String DOWNLOAD_DIR;
    private final String EXTENTION;
    private final String FILENAME;

    public RestClient(HashMap<String, Object> PARAMS,
                      String URL,
                      IRequest REQUEST,
                      ISuccess SUCCESS,
                      IFailure FAILURE,
                      IError ERROR,
                      RequestBody BODY,
                      File FILE,
                      String DOWNLOAD_DIR,
                      String EXTENTION,
                      String FILENAME) {
        this.PARAMS = PARAMS;
        this.URL = URL;
        this.REQUEST = REQUEST;
        this.SUCCESS = SUCCESS;
        this.FAILURE = FAILURE;
        this.ERROR = ERROR;
        this.BODY = BODY;
        this.FILE = FILE;
        this.DOWNLOAD_DIR = DOWNLOAD_DIR;
        this.EXTENTION = EXTENTION;
        this.FILENAME = FILENAME;
    }

//    public RestClient(HashMap<String, Object> PARAMS,
//                      String URL,
//                      IRequest REQUEST,
//                      ISuccess SUCCESS,
//                      IFailure FAILURE,
//                      IError ERROR,
//                      RequestBody BODY) {
//        this.PARAMS = PARAMS;
//        this.URL = URL;
//        this.REQUEST = REQUEST;
//        this.SUCCESS = SUCCESS;
//        this.FAILURE = FAILURE;
//        this.ERROR = ERROR;
//        this.BODY = BODY;
//    }

    public static RestClientBuilder create() {
        return new RestClientBuilder();
    }

RestClient中提供create方法,返回RestClientBuilder对象,RestClientBuilder内部提供build方法又重新将RestClient对象返回:


RestClientBuilder

最终调用地方就很简洁了:


image.png
上一篇下一篇

猜你喜欢

热点阅读