<轉>RxJava+Retrofit+OkHttp 懶人方式使用一

背景

之前學習完Retrofit+Rxjava之后寫了一篇關于封裝的博客,發出后受到大家的關注以及使用,由于不斷的完善之前的項目,所以決定把最新的項目封裝過程講解出來,供大家查看!

原博客地址:Rxjava+ReTrofit+okHttp深入淺出-終極封裝

懶人簡單的使用方式

為什么稱為懶人,因為你什么都不用做,直接按照一般案例寫rx和retrofit的###使用

20161024093019124.gif
  • 引入需要的包
 /*rx-android-java*/
    compile 'io.reactivex:rxjava:+'
    compile 'com.squareup.retrofit:adapter-rxjava:+'
    compile 'com.trello:rxlifecycle:+'
    compile 'com.trello:rxlifecycle-components:+'
    /*rotrofit*/
    compile 'com.squareup.retrofit2:retrofit:+'
    compile 'com.squareup.retrofit2:converter-gson:+'
    compile 'com.squareup.retrofit2:adapter-rxjava:+'
    compile 'com.google.code.gson:gson:+'
  • 創建一個service定義請求的接口
/**
 * service統一接口數據
 * Created by WZG on 2016/7/16.
 */
public interface HttpService {
    @POST("AppFiftyToneGraph/videoLink")
    Observable<RetrofitEntity> getAllVedioBy(@Body boolean once_no);
}
  • 創建一個retrofit對象
//手動創建一個OkHttpClient并設置超時時間
        okhttp3.OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(5, TimeUnit.SECONDS);

        Retrofit retrofit = new Retrofit.Builder()
                .client(builder.build())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(HttpManager.BASE_URL)
                .build();
  • http請求處理
        //加載框
        final ProgressDialog pd = new ProgressDialog(this);

        HttpService apiService = retrofit.create(HttpService.class);
        Observable<RetrofitEntity> observable = apiService.getAllVedioBy(true);
        observable.subscribeOn(Schedulers.io()).unsubscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                   new Subscriber<RetrofitEntity>() {
                   @Override
                   public void onCompleted() {
                   if (pd != null && pd.isShowing()) {
                             pd.dismiss();
                      }
                   }

                   @Override
                   public void onError(Throwable e) {
                       if (pd != null && pd.isShowing()) {
                              pd.dismiss();
                          }
                       }

                   @Override
                   public void onNext(RetrofitEntity retrofitEntity) {
                        tvMsg.setText("無封裝:\n" + retrofitEntity.getData().toString());
                   }

                   @Override
                   public void onStart() {
                         super.onStart();
                         pd.show();
                   }
                }
       );

源碼

源碼

終極封裝專欄

RxJava+Retrofit+OkHttp深入淺出-終極封裝專欄

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容