看一个例子:
先定义好接口
public interface APIInterface{
@GET("/admin/login")
Flowable<ResponseBody> getEntity(@Query("userName") String userName,
@Query("password") String password);
}
先看出问题的写法:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://10.0.2.2:8080")
.addConverterFactory(GsonConverterFactory.create())
.build();
APIInterface service = retrofit.create(APIInterface.class);
service.getEntity("aaa","123")
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new ResourceSubscriber<ResponseBody>() {
@Override
public void onNext(ResponseBody responseBody) {
Log.w("打印", "结果是"+responseBody.toString());
}
@Override
public void onError(Throwable t) {}
@Override
public void onComplete() {}
});
然后抛出异常:
解决办法:
gradle中倒包:
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.5.0'
代码中修改
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://10.0.2.2:8080")
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
...
...
看下RxJava2CallAdapterFactory.create()源码中都做了什么:
private RxJava2CallAdapterFactory(@Nullable Scheduler scheduler, boolean isAsync) {
this.scheduler = scheduler;
this.isAsync = isAsync;
}