前言
retrofit除了正常使用以外,还支持RxJava的模式来使用,此篇博客讲解如何使用RxJava模式下的retrofit
依赖
implementation 'com.squareup.retrofit2:retrofit:2.6.2' implementation 'com.squareup.retrofit2:converter-gson:2.4.0' //多了三个需要依赖的RxJava implementation 'com.squareup.retrofit2:adapter-rxjava2:2.4.0' implementation 'io.reactivex.rxjava2:rxjava:2.2.2' implementation 'io.reactivex.rxjava2:rxandroid:2.1.0' //提供 AndroidSchedulers.mainThread()
简单的Demo
创建接口类
public interface RxHttpList { @FormUrlEncoded @POST("test/login_test") Observable<LoginBean> login(@Field("number") String number, @Field("password") String password); }
创建Retrofit
private void initRxHttpBase() { mRetrofit = new Retrofit.Builder() .baseUrl("http://doclever.cn:8090/mock/5c3c6da33dce46264b24452b/") .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build(); }
请求网络
private void rxPostHttp() { RxHttpList rxHttpList = mRetrofit.create(RxHttpList.class); Observable<LoginBean> observable = rxHttpList.login("13113", "1131311"); observable.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<LoginBean>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(LoginBean loginBean) { Log.e(TAG, "onNext: 请求成功 code=" + loginBean.getCode()); Log.e(TAG, "onNext: 请求成功 message=" + loginBean.getMessage()); } @Override public void onError(Throwable e) { } @Override public void onComplete() { } }); }
RxJava模式下的取消网络请求
private void rxPostHttp() { RxHttpList rxHttpList = mRetrofit.create(RxHttpList.class); Observable<LoginBean> observable = rxHttpList.login("13113", "1131311"); observable.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<LoginBean>() { @Override public void onSubscribe(Disposable d) { //把Disposable引用到全局就可以用来取消网络请求 // d.dispose();//取消网络请求 } //略...... }); }
end