2

我想使用 retrofit2 和 rxjava3 但我看到以下错误

Caused by: java.lang.IllegalArgumentException: Could not locate call adapter for io.reactivex.rxjava3.core.Observable<java.lang.Object>.
      Tried:
       * retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
       * retrofit2.CompletableFutureCallAdapterFactory
       * retrofit2.DefaultCallAdapterFactory

此错误表示Rxjava 没有适配器,但我在下面的行中添加了它

.addCallAdapterFactory(RxJava2CallAdapterFactory.create())

public class ServiceGenerator {
  private static final String BASE_URL = "http://example.com/";
  private static final OkHttpClient okHttpClient = new OkHttpClient.Builder()

    .connectTimeout(30, TimeUnit.SECONDS)
    .writeTimeout(30, TimeUnit.SECONDS)
    .readTimeout(30, TimeUnit.SECONDS)
    .build();

  public static <S> S createServiceSample(Class<S> serviceClass) {
    Retrofit.Builder builder =
      new Retrofit.Builder()
        .client(okHttpClient)
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .addConverterFactory(GsonConverterFactory.create());
    builder.baseUrl(BASE_URL);
    Retrofit retrofit = builder.build();
    return retrofit.create(serviceClass);
  }

}

和我的 ApiInterface

public interface ApiInterface {
  @Headers("Content-Type: application/json")
  @GET("api/v1/movies?q=[]&page=[1]")
  Observable<Object> check();
}

并用于活动

  ApiInterface apiInterface = ServiceGenerator.createServiceSample(ApiInterface.class);
    Observable<Object> cryptoObservable = apiInterface.check();
    cryptoObservable.subscribeOn(Schedulers.newThread())
      .observeOn(AndroidSchedulers.mainThread())
      .subscribe(new Observer<Object>() {
        @Override
        public void onSubscribe(@NonNull Disposable d) {
          Log.i(TAG, "onSubscribe: ");
        }

        @Override
        public void onNext(@NonNull Object o) {
          Log.i(TAG, "onNext: " + new Gson().toJson(o));

        }

        @Override
        public void onError(@NonNull Throwable e) {
          Log.i(TAG, "onError: ");
        }

        @Override
        public void onComplete() {
          Log.i(TAG, "onComplete: ");
        }
      });

和 build.gradle

    implementation 'io.reactivex.rxjava3:rxandroid:3.0.0'
    implementation 'io.reactivex.rxjava3:rxjava:3.0.4'

    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'

    implementation 'com.google.code.gson:gson:2.8.2'
4

1 回答 1

5

您只需要在build.gradle中替换以下行

implementation 'com.squareup.retrofit2:adapter-rxjava3:2.9.0'

用这条线

implementation 'com.squareup.retrofit2:adapter-rxjava2:2.9.0'

替换ServiceGenerator中的以下行

.addCallAdapterFactory(RxJava3CallAdapterFactory.create())

用这条线

.addCallAdapterFactory(RxJava2CallAdapterFactory.create())

它对我有用

于 2020-07-23T13:26:31.667 回答