今年Android移動各大門戶網站最熱門的無非RxJava-Retrofit-OkHttp,因此準備強勢入手一波封裝,解決代碼複用性的問題,這篇先先來個簡單的壓壓驚,看看RxJava-Retrofit結合的使用基礎要點,後續會出一些列的專欄優化一套完善的請求封裝。html
爲何稱爲懶人,由於你什麼都不用作,直接按照通常案例寫rx和retrofit的使用java
/*rx-android-java*/
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定義請求的接口android
/** * service統一接口數據 * Created by WZG on 2016/7/16. */
public interface HttpService {
@POST("AppFiftyToneGraph/videoLink")
Observable<RetrofitEntity> getAllVedioBy(@Body boolean once_no);
}複製代碼
建立一個retrofit對象api
//手動建立一個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();複製代碼
// 加載框
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();
}
}
);複製代碼
傳送門-源碼地址優化