RxJava+Retrofit+OkHttp 深入浅出-终极封装一

时间:2021-08-25 17:46:43

背景

之前学习完Retrofit+Rxjava之后写了一篇关于封装的博客,发出后受到大家的关注以及使用,由于不断的完善之前的项目,所以决定把最新的项目封装过程讲解出来,供大家查看! 
原博客地址:Rxjava+ReTrofit+okHttp深入浅出-终极封装

效果

RxJava+Retrofit+OkHttp 深入浅出-终极封装一

懒人简单的使用方式

为什么称为懒人,因为你什么都不用做,直接按照一般案例写rx和retrofit的使用

  • 引入需要的包
    /*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:+'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 创建一个service定义请求的接口
/**
* service统一接口数据
* Created by WZG on 2016/7/16.
*/

public interface HttpService {
@POST("AppFiftyToneGraph/videoLink")
Observable<RetrofitEntity> getAllVedioBy(@Body boolean once_no);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 创建一个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();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 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();
}
}

);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35

终极封装专栏

RxJava+Retrofit+OkHttp深入浅出-终极封装专栏)


源码

传送门-源码地址


建议

如果你对这套封装有任何的问题和建议欢迎加入QQ群告诉我!