RxJava和Retrofit2的統一處理單個請求示例詳解

這篇文章主要給大家介紹了關於RxJava和Retrofit2的統一處理單個請求的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨着小編來一起學習學習吧

前言

RxJava和Retrofit2用了一段時間了,寫個小例子,分享出來,有什麼不對的地方還請大神在評論區指正。

什麼是Retrofit2

官網是這麼介紹的:

Retrofit adapts a Java interface to HTTP calls by using annotations on the declared methods to
define how requests are made。

我翻譯的可能不準確,他的大概意思是說:Retrofit 是一個 java 接口類,以註解的方式用於 HTTP 網絡請求。那下面我們一起來看看是怎麼使用的?

發現問題

最近在幫兄弟公司做一個資訊類的項目,使用了RxJava和Retrofit2這對黃金組合,在編寫代碼的過程中發現有很多很多的網絡請求都需要做.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).onErrorReturn()的處理,爲避免這樣,需要沉思。

解決問題

import android.util.Log;

import com.wei.caiqiwang.data.entity.BaseResponse;

import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class RxNet {
 /**
  * 統一處理單個請求
  */
 public static <T> Subscription request(Observable<BaseResponse<T>> observable, final RxNetCallBack<T> callBack) {
  return observable
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .onErrorReturn(new Func1<Throwable, BaseResponse<T>>() {
     @Override
     public BaseResponse<T> call(Throwable throwable) {
      Log.v("LinNetError",throwable.getMessage());
      callBack.onFailure(ExceptionHandle.handleException(throwable));
      return null;
     }
    })
    .subscribe(new Subscriber<BaseResponse<T>>() {
     @Override
     public void onCompleted() {

     }

     @Override
     public void onError(Throwable e) {

     }

     @Override
     public void onNext(BaseResponse<T> baseResponse) {
      if (baseResponse.getCode().equals("200")) {
       callBack.onSuccess(baseResponse.getData());
      } else {
       callBack.onFailure(baseResponse.getMsg());
      }
     }
    });

 }

 /**
  * 統一處理單個請求沒有 msg body
  */
 public static Subscription requestWithoutBody(Observable<BaseResponse> observable, final RxNetCallBack<String> callBack) {
  return observable
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .onErrorReturn(new Func1<Throwable, BaseResponse>() {
     @Override
     public BaseResponse call(Throwable throwable) {
      callBack.onFailure(ExceptionHandle.handleException(throwable));
      return null;
     }
    })
    .subscribe(new Subscriber<BaseResponse>() {
     @Override
     public void onCompleted() {

     }

     @Override
     public void onError(Throwable e) {

     }

     @Override
     public void onNext(BaseResponse baseResponse) {
      if (baseResponse.getCode().equals("200")) {
       callBack.onSuccess(baseResponse.getMsg());
      } else {
       callBack.onFailure(baseResponse.getMsg());
      }
     }
    });

 }
}

回調就是普通的回調

public interface RxNetCallBack<T> {
 /**
  * 數據請求成功
  *
  * @param data 請求到的數據
  */
 void onSuccess(T data);

 /**
  * 數據請求失敗
  */
 void onFailure(String msg);
}

錯誤異常處理(可能不全):

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:

import android.util.Log;


import com.wei.demo.data.AppConstants;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class ApiManager {

 private Retrofit client;

 private ApiManager() {
  client = new Retrofit.Builder()
    .baseUrl(AppConstants.Base_Url_Api_Test)
    .client(initClient())
    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
    .addConverterFactory(GsonConverterFactory.create())
    .build();
 }

 private static volatile DemoApi INSTANCE;

 public static DemoApi getInstance() {
  if (INSTANCE == null) {
   synchronized (ApiManager.class) {
    if (INSTANCE == null) {
     INSTANCE = new ApiManager().getApi();
    }
   }
  }
  return INSTANCE;
 }

 private DemoApi getApi() {
  return client.create(DemoApi.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("NetLog", message);
   }
  });
  //設定日誌級別
  httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
  //延時
  builder.addInterceptor(httpLoggingInterceptor)
    .connectTimeout(10, TimeUnit.SECONDS)
    .readTimeout(10, TimeUnit.SECONDS)
    .writeTimeout(10, TimeUnit.SECONDS);
  return builder.build();
 }
}

怎麼用?

 RxNet.request(ApiManager.getInstance().getUserMsg(map), new RxNetCallBack<List<MsgBean>>() {
   @Override
   public void onSuccess(List<MsgBean> data) {
    // 處理數據
   }

   @Override
   public void onFailure(String msg) {
    //出現了錯誤
    showToast(msg);
    
   }
  });

Demo https://github.com/FriendLin/NetRequestDemo (本地下載

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對神馬文庫的支持。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章