关于RxJava与Retrofit的封装

2018-03-10  本文已影响0人  有没有口罩给我一个

概述

目前RxJava和Retrofit结合使用已经是非常普遍了,网上关于这方面的文章也是层出不穷,其实大致的思想都是差不多的,今天我也来写一篇关于RxJava与Retrofit的文章,聊一聊关于RxJava与Retrofit的封装,尽可能的能让其适用于大部分项目,以供大家在学习这方面的时候多一份参考。

首先我们需要去定义一个对应接口的Service和返回结果的统一处理的实体类

public class HttpResult<T> {
  public int code;
  public String message;
  public T payload;
  public boolean status;

    public boolean isSuccess() {
        return code == 200;
    }
}

定义APIService

public interface APIService {
@GET("uri")
Flowable<HttpResult<PayloadBean>> getRegisterCode(@QueryMap Map<String, String> params);//请求验证码
}

定义封装Retrofit处理类

public class RetrofitHttpUtil {
private static final String BASE_URL = "baseurl";
public APIService apiService;
private static Retrofit retrofit = null;
private static OkHttpClient okHttpClient = null;

private Context mContext;

//缓存设置0不缓存
private boolean isUseCache;
private int maxCacheTime = 60;


public void setMaxCacheTime(int maxCacheTime) {
    this.maxCacheTime = maxCacheTime;
}

public void setUseCache(boolean useCache) {
    isUseCache = useCache;
}

public APIService getService() {
    if (apiService == null && retrofit != null) {
        apiService = retrofit.create(APIService.class);
    }
    return apiService;
}


public void init(Context context) {
    this.mContext = context;
    initOkHttp();
    initRetrofit();
    if (apiService == null) {
        apiService = retrofit.create(APIService.class);
    }
}

private void initOkHttp() {
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    builder.connectTimeout(15, TimeUnit.SECONDS);
    builder.readTimeout(20, TimeUnit.SECONDS);
    builder.writeTimeout(20, TimeUnit.SECONDS);
    //错误重连
    builder.retryOnConnectionFailure(true);
    okHttpClient = builder.build();

}

private void initRetrofit() {
    retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build();
}

public <T> void toSubscribe(Flowable<T> o, Subscriber<T> s) {
    o.subscribeOn(Schedulers.io())
            .unsubscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(s);
}

//统一处理请求结果

public class HttpResultFunc<T> implements Function<HttpResult<T>, T> {

    @Override
    public T apply(HttpResult<T> httpResult) throws Exception {
        Log.e("xixi", httpResult.code + "--" + httpResult.message + "");
        if (!httpResult.isSuccess()) {
            throw new APIException(httpResult.code, httpResult.message);
        }
        return httpResult.payload;
    }
}
}

定义API管理类

public class APIFactory<T> extends RetrofitHttpUtil {

public void getRegisterCode(final Map<String, String> params, final NetRequestAdapter<PayloadBean> calback) {
    Flowable<PayloadBean> registerCode = apiService.getRegisterCode(params)
            .map(new HttpResultFunc<PayloadBean>());
    toSubscribe(registerCode, calback);
}
}

定义适配器 将Subscriber适配为NetworkRequestCalback(只是自定义的回调)

public class NetRequestAdapter<T> implements Subscriber<T> {
private NetworkRequestCalback calback;

public NetRequestAdapter(NetworkRequestCalback calback) {
    this.calback = calback;
}

@Override
public void onSubscribe(Subscription s) {
 
    calback.onNetStart();
}

@Override
public void onError(Throwable throwable) {

    if (throwable instanceof SocketTimeoutException) {
        if (calback != null) {
            calback.onError(C.net.NETERROR, "网络中断,请检查您的网络状态");
        }
    } else if (throwable instanceof ConnectException) {
        if (calback != null) {
            calback.onError(C.net.NETERROR, "网络中断,请检查您的网络状态");
        }
    } else if (throwable instanceof APIException) {
        if (calback != null) {
            calback.onError(((APIException) throwable).getCode(), ((APIException) throwable).getMessage());
        }
    } else {
        if (calback != null) {
            throwable.printStackTrace();
            calback.onError(C.net.UNKONWERROR, "未知错误,请重试");
        }
    }
}

@Override
public void onNext(T t) {
    calback.onSuccess(t);
}

@Override
public void onComplete() {
 
    calback.onNetFinish();
}
}

如何使用:

 HashMap<String, String> params = new HashMap<>();
        params.put("account", mobile_register.getEditText().getText().toString());
        APIFactory<PayloadBean> responseHandle = new APIFactory();
        responseHandle.init(getContext());
        responseHandle.getRegisterCode(params, new NetRequestAdapter<PayloadBean>(this));

就到这里了

上一篇下一篇

猜你喜欢

热点阅读