背景
之前學(xué)習(xí)完Retrofit+Rxjava之后寫(xiě)了一篇關(guān)于封裝的博客葬毫,發(fā)出后受到大家的關(guān)注以及使用梗醇,由于不斷的完善之前的項(xiàng)目,所以決定把最新的項(xiàng)目封裝過(guò)程講解出來(lái)冶匹,供大家查看!
原博客地址:Rxjava+ReTrofit+okHttp深入淺出-終極封裝
懶人簡(jiǎn)單的使用方式
為什么稱為懶人节值,因?yàn)槟闶裁炊疾挥米鲠愎瑁苯影凑找话惆咐龑?xiě)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:+'
- 創(chuàng)建一個(gè)service定義請(qǐng)求的接口
/**
* service統(tǒng)一接口數(shù)據(jù)
* Created by WZG on 2016/7/16.
*/
public interface HttpService {
@POST("AppFiftyToneGraph/videoLink")
Observable<RetrofitEntity> getAllVedioBy(@Body boolean once_no);
}
- 創(chuàng)建一個(gè)retrofit對(duì)象
//手動(dòng)創(chuàng)建一個(gè)OkHttpClient并設(shè)置超時(shí)時(shí)間
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請(qǐng)求處理
//加載框
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("無(wú)封裝:\n" + retrofitEntity.getData().toString());
}
@Override
public void onStart() {
super.onStart();
pd.show();
}
}
);