使用 Dagger + Retrofit + RxJava 创建适配器错误

Create adapter error with Dagger + Retrofit + RxJava

我正在尝试使用 Retrofit 获取 Observable。我收到此错误:

Unable to create call adapter for rx.Observable for method AqicnApi.getHerePollutionObservable

这是我在 MainActivity 中遇到错误的地方:

Observable<Aqicn> aqicnObservable = aqicnApi.getHerePollutionObservable(getResources().getString(R.string.aqicn_token));

这是我的AqicnApi接口:

public interface AqicnApi {
    @GET("feed/here/")
    Call<Aqicn> getHerePollution(@Query("token") String token); // Query token parameter needed for API auth

    @GET("feed/here/")
    Observable<Aqicn> getHerePollutionObservable(@Query("token") String token); // Query token parameter needed for API auth
}

如果我尝试让我的数据返回一个 Aqicn 而不是一个 Observable<Aqicn> 使用它,它工作得很好 :

Call<Aqicn> call = aqicnApi.getHerePollution(getResources().getString(R.string.aqicn_token));

这是我的 ApiModule class 和 Retrofit 供应商

@Module
public class ApiModule {
    private String baseUrl;

    public ApiModule(String baseUrl) {
        if(baseUrl.trim() == "") {
            throw new IllegalArgumentException("API URL not valid");
        }
        this.baseUrl = baseUrl;
    }

    // Logging
    @Provides
    public OkHttpClient provideClient() {
        ...
    }

    //Retrofit
    @Provides
    public Retrofit provideRetrofit(String baseURL, OkHttpClient client) {
        return new Retrofit.Builder()
                .baseUrl(baseURL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    /**
     * Gets an instance of our Retrofit object calling the above methods then, using this Retrofit
     * object it creates an instance of AqicnApi interface by calling the create() method.
     * @return
     */
    @Provides
    public AqicnApi provideApiService() {
        return provideRetrofit(baseUrl, provideClient()).create(AqicnApi.class);
    }
}

我忘了什么?

Rx support in Retrofit 是必须添加的插件,默认没有。

将此库添加到您的项目中 build.gradle:

compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'

并向 Retrofit 构建者提供 Rx 适配器工厂:

@Provides
public Retrofit provideRetrofit(String baseURL, OkHttpClient client) {
    return new Retrofit.Builder()
            .baseUrl(baseURL)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            //You must provide Rx adapter factory to Retrofit
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .build();
}