当retrofit2与rxjava3连用时(截止发博客时间,很多搜索结果还是retrofit2+rxjava2,而retrofit2+rxjava3的还是比较少的,所以特此记录一下),按照常规的写法,在运行时会报错:Unable to create call adapter for rx.Observable<java.lang.String>
先看一下发生错误的配置是:
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
implementation "io.reactivex.rxjava3:rxjava:3.0.7"
implementation 'io.reactivex:rxandroid:1.2.1'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.squareup.retrofit2:adapter-rxjava3:2.9.0'
implementation 'com.squareup.okhttp3:logging-interceptor:4.10.0-RC1'
implementation 'com.squareup.retrofit2:converter-scalars:2.9.0'
}
这里粗心了,漏了一个"io.reactivex:rxandroid"没有升级成rxjava3的,所以报了如上错误,
改正之后:
implementation 'io.reactivex.rxjava3:rxandroid:3.0.0'
就可以了。
完整配置如下(一定要配套使用,否则会报错,就像我上面那样):
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
implementation "io.reactivex.rxjava3:rxjava:3.0.7"
implementation 'io.reactivex.rxjava3:rxandroid:3.0.0'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.squareup.retrofit2:adapter-rxjava3:2.9.0'
implementation 'com.squareup.okhttp3:logging-interceptor:4.10.0-RC1'
implementation 'com.squareup.retrofit2:converter-scalars:2.9.0'
}
再简单举例一下,初始化Retrofit时别导错包了:
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
...
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create()) //设置 Json 转换器
.addCallAdapterFactory(RxJava3CallAdapterFactory.create()).build(); //RxJava3 适配器
HttpService httpService = retrofit.create(HttpService.class);
httpService.getData()
.subscribeOn(Schedulers.io()) //rxjava3的Schedulers
.observeOn(AndroidSchedulers.mainThread()) // rxjava3的AndroidSchedulers
.subscribe(new Observer<String>() { // rxjava3.core.Observer
@Override
public void onSubscribe(@NonNull Disposable d) {
}
@Override
public void onNext(@NonNull String s) {
}
@Override
public void onError(@NonNull Throwable e) {
}
@Override
public void onComplete() {
}
});
...
HttpService API接口中的getData方法 返回的Observable 类型是:
import io.reactivex.rxjava3.core.Observable;
请仔细对照,只要这些都保证一致,sync之后再run,完美运行项目~
如有帮助,记得点赞三连~