RxJava2和Retrofit2封裝教程(整潔、簡單、實(shí)用)
前言
RxJava2與Retrofit2是老搭檔了,之前寫了一篇《RxJava和Retrofit2的統(tǒng)一處理單個(gè)請求》,是用的Rxjava1.0,本次使用Rxjava2.0與Retrofit2進(jìn)行封裝,一樣整潔、簡單、實(shí)用。Rxjava2相比Rxjava1優(yōu)化和改動不少了東西,網(wǎng)上有很多大神寫的文章,這里就不粘貼復(fù)制了。封裝的過程有什么問題、疑問,請?jiān)谙路搅粞浴?br />
下面話不多說了,來一起看看詳細(xì)的介紹吧
封裝教程如下:
核心網(wǎng)絡(luò)請求:
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 {
/**
* 統(tǒng)一處理單個(gè)請求
*
* @param observable
* @param callBack
* @param <T>
*/
public static <T> Disposable request(Observable<BaseResponse<T>> observable, final RxNetCallBack<T> callBack) {
return observable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.onErrorReturn(new Function<Throwable, BaseResponse<T>>() {
@Override
public BaseResponse<T> apply(Throwable throwable) {
Log.e("LinNetError", throwable.getMessage());
callBack.onFailure(ExceptionHandle.handleException(throwable));
return null;
}
})
.subscribe(new Consumer<BaseResponse<T>>() {
@Override
public void accept(BaseResponse<T> tBaseResponse) {
if (tBaseResponse.getCode().equals("200")) {
callBack.onSuccess(tBaseResponse.getData());
} else {
callBack.onFailure(tBaseResponse.getMsg());
}
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) {
Log.e("LinNetError", "單個(gè)請求的錯(cuò)誤" + throwable.getMessage());
}
});
}
/**
* 統(tǒng)一處理單個(gè)請求
* 返回?cái)?shù)據(jù)沒有body
*/
public static Disposable requestWithoutBody(Observable<BaseResponse> observable,
final RxNetCallBack<String> callBack) {
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<BaseResponse>() {
@Override
public void accept(BaseResponse baseResponse) {
if (baseResponse.getCode().equals("200")) {
callBack.onSuccess(baseResponse.getMsg());
} else {
callBack.onFailure(baseResponse.getMsg());
}
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) {
Log.v("LinNetError", "單個(gè)請求的錯(cuò)誤:沒有body" + throwable.getMessage());
}
});
}
}
回調(diào)就是普通的泛型的回調(diào)
package com.lin.netrequestdemo.data;
public interface RxNetCallBack<T> {
/**
* 數(shù)據(jù)請求成功
*
* @param data 請求到的數(shù)據(jù)
*/
void onSuccess(T data);
/**
* 數(shù)據(jù)請求失敗
*/
void onFailure(String msg);
}
錯(cuò)誤異常處理(可能不全):
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 = "網(wǎng)絡(luò)錯(cuò)誤";
break;
}
return errorMsg + ":" + httpException.code();
} else if (e instanceof JsonParseException || e instanceof JSONException || e instanceof ParseException) {
return "解析錯(cuò)誤";
} else if (e instanceof ConnectException) {
return "連接失敗";
} else if (e instanceof javax.net.ssl.SSLHandshakeException) {
return "證書驗(yàn)證失敗";
} else if (e instanceof ConnectTimeoutException) {
return "連接超時(shí)";
} else if (e instanceof java.net.SocketTimeoutException) {
return "連接超時(shí)";
} else {
return "未知錯(cuò)誤";
}
}
}
然后就是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);
}
});
//設(shè)定日志級別
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
//延時(shí)
builder.addInterceptor(httpLoggingInterceptor)
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS);
return builder.build();
}
}
怎么用:
showLoading();
Map<String, String> map = new ArrayMap<>();
map.put("action", "pricetrend");
addCompositeDisposable(RxNet.request(ApiManager.getInstance().getCat(map), new RxNetCallBack<List<CatBean>>() {
@Override
public void onSuccess(List<CatBean> data) {
hideLoading();
showToast("獲取列表成功" + data.get(0).toString());
}
@Override
public void onFailure(String msg) {
hideLoading();
showToast(msg);
}
}));
Demo奉上 https://github.com/FriendLin/NetRequestDemo(本地下載)
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關(guān)文章
Flutter?SystemChrome控制應(yīng)用程序的系統(tǒng)級別行為
這篇文章主要為大家介紹了Flutter?SystemChrome用來控制應(yīng)用程序的系統(tǒng)級別行為步驟詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-05-05
Android Jetpack架構(gòu)組件Lifecycle詳解
這篇文章主要介紹了Android Jetpack架構(gòu)組件Lifecycle詳解,Lifecycle是Jetpack架構(gòu)組件中用來感知生命周期的組件,使用Lifecycles可以幫助我們寫出和生命周期相關(guān)更簡潔更易維護(hù)的代碼。對此感興趣的小伙伴可以來學(xué)習(xí)一下2020-07-07
Android用PopupWindow實(shí)現(xiàn)自定義Dailog
這篇文章主要為大家詳細(xì)介紹了Android用PopupWindow實(shí)現(xiàn)自定義Dailog的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-01-01
OpenGL Shader實(shí)例分析(8)彩色光圈效果
這篇文章主要為大家詳細(xì)介紹了OpenGL Shader實(shí)例分析第8篇,彩色光圈效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-02-02
Android 中HttpURLConnection與HttpClient使用的簡單實(shí)例
這篇文章介紹了Android 中HttpURLConnection與HttpClient使用的簡單實(shí)例,有需要的朋友可以參考一下2013-10-10
android實(shí)現(xiàn)http中請求訪問添加cookie的方法
這篇文章主要介紹了android實(shí)現(xiàn)http中請求訪問添加cookie的方法,實(shí)例分析了兩種添加cookie的技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-10-10-
最新評論

