RxJava2和Retrofit2封装教程(整洁、简单、实用)

网友投稿 311 2023-01-19


RxJava2和Retrofit2封装教程(整洁、简单、实用)

前言

Rxjava2与Retrofit2是老搭档了,之前写了一篇《RxJava和Retrofit2的统一处理单个请求》,是用的Rxjava1.0,本次使用Rxjava2.0与Retrofit2进行封装,一样整洁、简单、实用。Rxjava2相比Rxjava1优化和改动不少了东西,网上有很多大神写的文章,这里就不粘贴复制了。封装的过程有什么问题、疑问,请在下方留言。

下面话不多说了,来一起看看详细的介绍吧

封装教程如下:

核心网络请求:

package com.lin.netrequestdemo.data;

import android.util.Log;

import io.reactivex.Observable;

import io.reactivex.android.schedulers.AndroidSchedulers;

import io.reactivex.disposables.Disposable;

import io.reactivex.functions.Consumer;

import io.reactivex.functions.Function;

import io.reactivex.schedulers.Schedulers;

public class RxNet {

/**

* 统一处理单个请求

*

* @param observable

* @param callBack

* @param

*/

public static Disposable request(Observable> observable, final RxNetCallBack callBack) {

return observable.subscribeOn(Schedulers.io())

.observeOn(AndroidSchedulers.mainThread())

.onErrorReturn(new Function>() {

@Override

public BaseResponse apply(Throwable throwable) {

Log.e("LinNetError", throwable.getMessage());

callBack.onFailure(ExceptionHandle.handleException(throwable));

return null;

}

})

.subscribe(new Consumer>() {

@Override

public void accept(BaseResponse tBaseResponse) {

if (tBaseResponse.getCode().equals("200")) {

callBack.onSuccess(tBaseResponse.getData());

} else {

callBack.onFailure(tBaseResponse.getMsg());

}

}

}, new Consumer() {

@Override

public void accept(Throwable throwable) {

Log.e("LinNetError", "单个请求的错误" + throwable.getMessage());

}

});

}

/**

* 统一处理单个请求

* 返回数据没有body

*/

public static Disposable requestWithoutBody(Observable observable,

final RxNetCallBack callBack) {

return observable.subscribeOn(Schedulers.io())

.observeOn(AndroidSchedulers.mainThread())

.onErrorReturn(new Function() {

@Override

public BaseResponse apply(Throwable throwable) {

Log.v("LinNetError", throwable.getMessage());

callBack.onFailure(ExceptionHandle.handleException(throwable));

return null;

}

})

.subscribe(new Consumer() {

@Override

public void accept(BaseResponse baseResponse) {

if (baseResponse.getCode().equals("200")) {

callBack.onSuccess(baseResponse.getMsg());

} else {

callBack.onFailure(baseResponse.getMsg());

}

}

}, new Consumer() {

@Override

public void accept(Throwable throwable) {

Log.v("LinNetError", "单个请求的错误:没有body" + throwable.getMessage());

}

});

}

}

回调就是普通的泛型的回调

package com.lin.netrequestdemo.data;

public interface RxNetCallBack {

/**

* 数据请求成功

*

* @param data 请求到的数据

*/

void onSuccess(T data);

/**

* 数据请求失败

*/

void onFailure(String msg);

}

错误异常处理(可能不全):

package com.lin.netrequestdemo.data;

import android.net.ParseException;

import com.google.gson.jsonParseException;

import org.apache.http.conn.ConnectTimeoutException;

import org.json.JSONException;

import java.net.ConnectException;

import retrofit2.HttpException;

public class ExceptionHandle {

private static final int UNAUTHORIZED = 401;

private static final int FORBIDDEN = 403;

private static final int NOT_FOUND = 404;

private static final int REQUEST_TIMEOUT = 408;

private static final int INTERNAL_SERVER_ERROR = 500;

private static final int BAD_GATEWAY = 502;

private static final int SERVICE_UNAVAILABLE = 503;

private static final int GATEWAY_TIMEOUT = 504;

public static String handleException(Throwable e) {

String errorMsg;

if (e instanceof HttpException) {

HttpException httpException = (HttpException) e;

switch (httpException.code()) {

case UNAUTHORIZED:

case FORBIDDEN:

case NOT_FOUND:

case REQUEST_TIMEOUT:

case GATEWAY_TIMEOUT:

case INTERNAL_SERVER_ERROR:

case BAD_GATEWAY:

case SERVICE_UNAVAILABLE:

default:

errorMsg = "网络错误";

break;

}

return errorMsg + ":" + httpException.code();

} else if (e instanceof JsonParseException || e instanceof JSONException || e instanceof ParseException) {

return "解析错误";

} else if (e instanceof ConnectException) {

return "连接失败";

} else if (e instanceof javax.net.ssl.SSLHandshakeException) {

return "证书验证失败";

} else if (e instanceof ConnectTimeoutException) {

return "连接超时";

} else if (e instanceof java.net.SocketTimeoutException) {

return "连接超时";

} else {

return "未知错误";

}

}

}

然后就是ApiManager:

package com.lin.netrequestdemo.data.api;

import android.util.Log;

import com.lin.netrequestdemo.data.AppConstants;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;

import okhttp3.logging.HttpLoggingInterceptor;

import retrofit2.Retrofit;

import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

import retrofit2.converter.gson.GsonConverterFactory;

public class ApiManager {

private Retrofit client;

private ApiManager() {

client = new Retrofit.Builder()

.baseUrl(AppConstants.Base_Url_Test)

.client(initClient())

.addCallAdapterFactory(RxJava2CallAdapterFactory.create())

.addConverterFactory(GsonConverterFactory.create())

.build();

}

private static volatile MallApi INSTANCE;

public static MallApi getInstance() {

if (INSTANCE == null) {

synchronized (ApiManager.class) {

if (INSTANCE == null) {

INSTANCE = new ApiManager().getMallApi();

}

}

}

return INSTANCE;

}

private MallApi getMallApi() {

return client.create(MallApi.class);

}

private static OkHttpClient initClient() {

OkHttpClient.Builder builder = new OkHttpClient.Builder();

//声明日志类

HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {

@Override

public void log(String message) {

Log.v("LinNet", message);

}

});

//设定日志级别

httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

//延时

builder.addInterceptor(httpLoggingInterceptor)

.connectTimeout(10, TimeUnit.SECONDS)

.readTimeout(10, TimeUnit.SECONDS)

.writeTimeout(10, TimeUnit.SECONDS);

return builder.build();

}

}

怎么用:

showLoading();

Map map = new ArrayMap<>();

map.put("action", "pricetrend");

addCompositeDisposable(RxNet.request(ApiManager.getInstance().getCat(map), new RxNetCallBack>() {

@Override

public void onSuccess(List data) {

hideLoading();

showToast("获取列表成功" + data.get(0).toString());

}

@Override

public void onFailure(String msg) {

hideLoading();

showToast(msg);

}

}));

Demo奉上 https://github.com/FriendLin/NetRequestDemo(本地下载)

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对我们的支持。


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:实现接口并继承类(接口的继承和类的继承)
下一篇:接口管理工具导入项目(开源api接口管理工具)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~