
前言
RxJava2、Retrofit2火了有一段时间了,前段时间给公司的项目引入了这方面相关的技术,在此记录一下相关封装的思路。
需求
封装之前要先明白需要满足哪些需求。
RxJava2衔接Retrofit2 Retrofit2网络框架异常的统一处理 兼容fastJson(可选) RxJava2内存泄漏的处理 异步请求加入Loading Dialog依赖
implementation 'io.reactivex.rxjava2:rxandroID:2.0.1' implementation 'io.reactivex.rxjava2:rxjava:2.1.3' implementation 'com.squareup.retrofit2:retrofit:2.3.0' implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0' implementation 'com.squareup.okhttp3:okhttp:3.9.0' implementation 'com.trello.rxlifecycle2:rxlifecycle-components:2.2.0' implementation 'com.alibaba:fastJson:1.1.59.androID'//可选其它框架比如Gson
RxJava2衔接Retrofit2
先封装一个网络框架的管理类,方便调用
public class Rxhttp { private final String BASE_URL = "https://github.com/"; private Map<String,Retrofit> mRetrofitMap = new HashMap<>(); private Rxhttp() { } /** * 单例模式 * @return */ public static Rxhttp getInstance() { return RxhttpHolder.sInstance; } private static class RxhttpHolder{ private final static Rxhttp sInstance = new Rxhttp(); } public Retrofit getRetrofit(String serverUrl) { Retrofit retrofit; if (mRetrofitMap.containsKey(serverUrl)) { retrofit = mRetrofitMap.get(serverUrl); } else { retrofit = createRetrofit(serverUrl); mRetrofitMap.put(serverUrl,retrofit); } return retrofit; } public SyncServerService getSyncServer(){ return getRetrofit(BASE_URL).create(SyncServerService.class); } /** * * @param baseUrl baseUrl要以/作为结尾 eg:https://github.com/ * @return */ private Retrofit createRetrofit(String baseUrl) { OkhttpClIEnt clIEnt = new OkhttpClIEnt().newBuilder() .readTimeout(30,TimeUnit.SECONDS) .connectTimeout(30,TimeUnit.SECONDS) .retryOnConnectionFailure(true) .build(); return new Retrofit.Builder() .baseUrl(baseUrl) .addConverterFactory(FastJsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .clIEnt(clIEnt) .build(); }}Restful风格接口
public interface SyncServerService { @GET("service/mobile/IsLatestVersion.ashx") Observable<Response<String>> getLatestVersion(@query("SoftwareID") String SoftwareID,@query("ClIEntVersion") String ClIEntVersion);}服务端返回的基本类型,在导入类的时候特别需要注意区分该Response类型
public class Response<T> { public int ret;//约定 -1为server返回数据异常 200为正常范围 public String msg; public T data; public int getRet() { return ret; } public voID setRet(int ret) { this.ret = ret; } public String getMsg() { return msg; } public voID setMsg(String msg) { this.msg = msg; } public T getData() { return data; } public voID setData(T data) { this.data = data; }}fastJson的支持
由于项目中采用了fastJson,square尚未实现对fastJson的支持,但是保留了代码的扩展,这边可以自己封装一下fastJson的转换器。
public class FastJsonConverterFactory extends Converter.Factory { private final SerializeConfig mSerializeConfig; private FastJsonConverterFactory(SerializeConfig serializeConfig) { this.mSerializeConfig = serializeConfig; } public static FastJsonConverterFactory create() { return create(SerializeConfig.getGlobalinstance()); } public static FastJsonConverterFactory create(SerializeConfig serializeConfig) { return new FastJsonConverterFactory(serializeConfig); } @OverrIDe public Converter<?,Requestbody> requestbodyConverter(Type type,Annotation[] parameterannotations,Annotation[] methodAnnotations,Retrofit retrofit) { return new FastJsonRequestbodyConverter<>(mSerializeConfig); } @OverrIDe public Converter<ResponseBody,?> responseBodyConverter(Type type,Annotation[] annotations,Retrofit retrofit) { return new FastJsonResponseBodyConvert<>(type); }}final class FastJsonRequestbodyConverter<T> implements Converter<T,Requestbody> { private final MediaType MEDIA_TYPE = MediaType.parse("application/Json; charset=UTF-8"); private SerializeConfig mSerializeConfig; public FastJsonRequestbodyConverter(SerializeConfig serializeConfig) { this.mSerializeConfig = serializeConfig; } @OverrIDe public Requestbody convert(T value) throws IOException { return Requestbody.create(MEDIA_TYPE,JsON.toJsONBytes(value,mSerializeConfig)); }}final class FastJsonResponseBodyConvert<T> implements Converter<ResponseBody,T> { private Type mType; public FastJsonResponseBodyConvert(Type type) { this.mType = type; } @OverrIDe public T convert(ResponseBody value) throws IOException { return JsON.parSEObject(value.string(),mType); }}数据返回统一处理
public abstract class BaSEObserver<T> implements Observer<Response<T>> { @OverrIDe public final voID onNext(@NonNull Response<T> result) { if (result.getRet() == -1) { onFailure(new Exception(result.getMsg()),result.getMsg());//该异常可以汇报服务端 } else { onSuccess(result.getData()); } } @OverrIDe public voID onError(@NonNull Throwable e) { onFailure(e,RxExceptionUtil.exceptionHandler(e)); } @OverrIDe public voID onComplete() { } @OverrIDe public voID onSubscribe(@NonNull disposable d) { } public abstract voID onSuccess(T result); public abstract voID onFailure(Throwable e,String errorMsg);}下面加入了异常处理类
public class RxExceptionUtil { public static String exceptionHandler(Throwable e){ String errorMsg = "未知错误"; if (e instanceof UnkNownHostException) { errorMsg = "网络不可用"; } else if (e instanceof SocketTimeoutException) { errorMsg = "请求网络超时"; } else if (e instanceof httpException) { httpException httpException = (httpException) e; errorMsg = convertStatusCode(httpException); } else if (e instanceof ParseException || e instanceof JsONException || e instanceof com.alibaba.fastJson.JsONException) { errorMsg = "数据解析错误"; } return errorMsg; } private static String convertStatusCode(httpException httpException) { String msg; if (httpException.code() >= 500 && httpException.code() < 600) { msg = "服务器处理请求出错"; } else if (httpException.code() >= 400 && httpException.code() < 500) { msg = "服务器无法处理请求"; } else if (httpException.code() >= 300 && httpException.code() < 400) { msg = "请求被重定向到其他页面"; } else { msg = httpException.message(); } return msg; }}异步请求加入Loading Dialog
这个时候我们可以根据自己项目中统一封装的dialog自行扩展BaSEObserver
public abstract class ProgressObserver<T> extends BaSEObserver<T>{ private MaterialDialog mMaterialDialog; private Context mContext; private String mloadingText; public ProgressObserver(Context context){ this(context,null); } public ProgressObserver(Context context,String loadingText){ mContext = context; mloadingText = loadingText; } @OverrIDe public voID onSubscribe(@NonNull disposable d) { if (!d.isdisposed()) { mMaterialDialog = new MaterialDialog.Builder(mContext).content(mloadingText == null ? "正在加载中..." : mloadingText).isProgress(true).build(); mMaterialDialog.show(); } } @OverrIDe public voID onComplete() { if (mMaterialDialog != null) { mMaterialDialog.dismiss(); } } @OverrIDe public voID onError(@NonNull Throwable e) { super.onError(e); if (mMaterialDialog != null) { mMaterialDialog.dismiss(); } }}加入调度类,方便调用线程切换和解决内存泄漏的问题
public class RxSchedulers { public static <T> Observabletransformer<T,T> observableIO2Main(final Context context) { return upstream -> { Observable<T> observable = upstream.subscribeOn(Schedulers.io()) .observeOn(AndroIDSchedulers.mainThread()); return composeContext(context,observable); }; } public static <T> Observabletransformer<T,T> observableIO2Main(final RxFragment fragment) { return upstream -> upstream.subscribeOn(Schedulers.io()) .observeOn(AndroIDSchedulers.mainThread()).compose(fragment.<T>bindTolifecycle()); } private static <T> ObservableSource<T> composeContext(Context context,Observable<T> observable) { if(context instanceof RxActivity) { return observable.compose(((RxActivity) context).bindUntilEvent(ActivityEvent.DESTROY)); } else if(context instanceof RxFragmentActivity){ return observable.compose(((RxFragmentActivity) context).bindUntilEvent(ActivityEvent.DESTROY)); }else if(context instanceof RxAppCompatActivity){ return observable.compose(((RxAppCompatActivity) context).bindUntilEvent(ActivityEvent.DESTROY)); }else { return observable; } }}讲了那么多,那么如何使用这个封装呢?下面来看下如何使用。
Rxhttp.getInstance().getSyncServer().getLatestVersion("1","1.0.0") .compose(RxSchedulers.observableIO2Main(this)) .subscribe(new ProgressObserver<String>(this) { @OverrIDe public voID onSuccess(String result) { Toast.makeText(MainActivity.this,result,Toast.LENGTH_SHORT).show(); } @OverrIDe public voID onFailure(Throwable e,String errorMsg) { } });是不是封装后的代码显得更为简洁一点呢?以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。
总结以上是内存溢出为你收集整理的详解RxJava2 Retrofit2 网络框架简洁轻便封装全部内容,希望文章能够帮你解决详解RxJava2 Retrofit2 网络框架简洁轻便封装所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)