RxJavaCallAdapterFactory 无法转换为 Factory

RxJavaCallAdapterFactory cannot be converted to Factory

我正在尝试按照本文中的指南使用 Retrofit 2 和 RxJava https://inthecheesefactory.com/blog/retrofit-2.0/en

在“RxJava 与 CallAdapter 的集成”部分 " 解释了如何使用 RxJava 进行改造

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("http://api.nuuneoi.com/base/")
    .addConverterFactory(GsonConverterFactory.create())
    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
    .build();

但是在编译过程中出现如下错误:

Error:(63, 71) error: incompatible types: RxJavaCallAdapterFactory cannot be converted to Factory

我该如何解决? 谢谢

确保您对主 Retrofit 依赖项、Gson 转换器依赖项和 RxJava 适配器依赖项使用相同的 groupId 和版本。

我猜你的看起来像这样:

compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile 'com.squareup.retrofit:adapter-rxjava:2.0.0-beta2'

(注意他们使用不同的groupIds和版本号)

它们应该看起来都一样:

compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2'

当前添加 "com.squareup.retrofit:adapter-rxjava:2.0.0" 出现以下错误

Error:Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug'. > com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK META-INF/rxjava.properties

但是,相反,添加 "compile 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0",使打包成功

将您的改装 rxjava 适配器更改为

  implementation "com.squareup.retrofit2:adapter-rxjava2:$retrofit_version"

并将您的 CallAdapterFactory 更改为

.addCallAdapterFactory(RxJava2CallAdapterFactory.create())

看起来像这样

.baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();

使用更新的和最新的库。

// retrofit
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    implementation 'com.squareup.okhttp3:okhttp:4.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    implementation 'com.squareup.retrofit2:adapter-rxjava3:2.9.0'

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

注意 :: RxJava3CallAdapterFactory.create() 而不是 RxJava2CallAdapterFactory.create()

Retrofit.Builder()
            .baseUrl("https://datanapps.com")
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
            .build()