2、RxJava2 & Retrofit2 封装实践 初始化

时间:2022-04-10 17:50:57

RxJava2&Retrofit2的基本实现

RxJava2 & Retrofit2 & Rxlifecycle

依赖

    compile 'com.squareup.okhttp3:okhttp:3.7.0'

compile 'com.squareup.retrofit2:retrofit:2.2.0'
compile 'com.squareup.retrofit2:converter-gson:2.2.0'
compile 'com.squareup.retrofit2:adapter-rxjava2:2.2.0'

compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'io.reactivex.rxjava2:rxjava:2.0.8'

compile 'com.trello.rxlifecycle2:rxlifecycle:2.0.1'
// If you want to bind to Android-specific lifecycles
compile 'com.trello.rxlifecycle2:rxlifecycle-android:2.0.1'
// If you want pre-written Activities and Fragments you can subclass as providers
compile 'com.trello.rxlifecycle2:rxlifecycle-components:2.0.1'

HTTPCENTER

public static final String SERVICE = "http://xxxa.com/web/";
public static final String TOYS_SERVICE = "http://api.xxxb.com/";

@StringDef({SERVICE, TOYS_SERVICE})
@Retention(RetentionPolicy.SOURCE)
public @interface HOST {
}


/**
* 为了拓展性(切换Host),直接传入Retrofit.Builder
* 要求传入的Retrofit.Builder是单例
*
* @param builder
* @return
*/

protected static Retrofit getRetrofit(Retrofit.Builder builder) {
return builder.addConverterFactory(GsonConverterFactory.create(new Gson()))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(initOkHttpClient())
.build();
}

protected static Retrofit.Builder getBuilder(@HOST String host) {
do {

if (TextUtils.equals(host, SERVICE)) {
return BuilderHolder.builder;
}
if (TextUtils.equals(host, TOYS_SERVICE)) {
return BuilderHolder.toyBuilder;
}
} while (false);
return null;
}

private static class BuilderHolder {
private static Retrofit.Builder builder = new Retrofit.Builder().baseUrl(SERVICE);
private static Retrofit.Builder toyBuilder = new Retrofit.Builder().baseUrl(TOYS_SERVICE);

}

/**
* 用于请求的Retrofit
*
* @return
*/

protected static Retrofit getRetrofitDm() {
return getRetrofit(getBuilder(SERVICE));
}

protected static Retrofit getRetrofitToys() {
return getRetrofit(getBuilder(TOYS_SERVICE));
}

public static HTTPService getService(@HOST String host) {
do {

if (TextUtils.equals(host, SERVICE)) {
return ServiceHolder.DMSERVICE;
}
if (TextUtils.equals(host, TOYS_SERVICE)) {
return ServiceHolder.TOYSERVICE;
}
} while (false);
return null;
}

private static class ServiceHolder {
static HTTPService DMSERVICE = getRetrofitDm().create(HTTPService.class);
static HTTPService TOYSERVICE = getRetrofitToys().create(HTTPService.class);
}


/**
* client
*
* @return
*/

private static OkHttpClient initOkHttpClient() {
OkHttpClient.Builder client = new OkHttpClient().newBuilder();
client.retryOnConnectionFailure(true);
client.connectTimeout(1, TimeUnit.MINUTES);
client.readTimeout(1, TimeUnit.MINUTES);
client.writeTimeout(1, TimeUnit.MINUTES);
return client.build();
}
  • 根据HOST初始化HTTPService,都实现了单例
    • 构建RetrofitBuilder
    • 根据Builder创建HTTPService
  • 创建OkhttpClient

HTTPService

public interface HTTPService {

/**
* 发现-推荐-时间轴
*
* @param token
* @param offset
* @param limit
* @return
*/

@GET("v2/index/list")
Observable<TimeLineModel> requestRecommendTimeLine(@Query("offset") int offset, @Query("limit") int limit);


@GET("index.php?r=message/heart")
Observable<Heart> heart();

}

Activity请求

private void dm() {
HTTPCenter.getService(HTTPCenter.SERVICE).heart()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()) //切换线程
.compose(MainActivity.this.bindToLifecycle()) //绑定生命周期
.doOnSubscribe(new Consumer<Disposable>() {
@Override
public void accept(@NonNull Disposable disposable) throws Exception {
Toast.makeText(MainActivity.this,"dm start",Toast.LENGTH_SHORT).show();
}
}).doOnTerminate(new Action() {
@Override
public void run() throws Exception {
Toast.makeText(MainActivity.this,"dm end",Toast.LENGTH_SHORT).show();
}
}).subscribe(new Consumer<Heart>() {
@Override
public void accept(@NonNull Heart heart) throws Exception {
if(heart != null) {
tvDesc.setText(heart.toString());
}
}
});
}

private void toys() {
HTTPCenter.getService(HTTPCenter.TOYS_SERVICE).requestRecommendTimeLine(1,20).map(new Function<TimeLineModel, TimeLineModel>() {
@Override
public TimeLineModel apply(@NonNull TimeLineModel timeLineModel) throws Exception {
return timeLineModel;
}
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.compose(MainActivity.this.bindToLifecycle())
.subscribe(new Observer<TimeLineModel>() {
@Override
public void onSubscribe(Disposable d) {

}

@Override
public void onNext(TimeLineModel timeLineModel) {
tvDesc.setText(timeLineModel.toString());
}

@Override
public void onError(Throwable e) {

}

@Override
public void onComplete() {

}
});
}

compose(MainActivity.this.bindToLifecycle())RxlifecycleActivity需要继承RxAppCompatActivity
RxLifecycle使用详情

好了,现在基本实现了Rxjava2 & Retrofit2进行网络请求,但是太初级了。下面我们来进行一点点封装~