前言
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 staticDisposable request(Observable<BaseResponse > observable, final RxNetCallBack callBack) {
return observable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.onErrorReturn(new Function<Throwable, BaseResponse>() {
@Override
public BaseResponseapply(Throwable throwable) {
Log.e("LinNetError", throwable.getMessage());
callBack.onFailure(ExceptionHandle.handleException(throwable));
return null;
}
})
.subscribe(new Consumer<BaseResponse>() {
@Override
public void accept(BaseResponsetBaseResponse) {
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 RxNetCallBackcallBack) {
return observable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.onErrorReturn(new Function<Throwable, BaseResponse>() {
@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());
}
});