0

I'm trying to get an Observable using Retrofit. I'm getting this error :

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

This is where I'm getting the error in my MainActivity :

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

This is my AqicnApi interface :

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
}

If I try to get my data returning an Aqicn and not an Observable<Aqicn> using this, it works perfectly :

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

This is my ApiModule class with Retrofit provider

@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);
    }
}

What i forgot ?

Laurent
  • 1,661
  • 16
  • 29

1 Answers1

1

Rx support in Retrofit is a plugin that you must add, it is not there by default.

add this library to your project in your build.gradle:

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

and provide the Rx adapter factory to Retrofit builder:

@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();
}
yosriz
  • 10,147
  • 2
  • 24
  • 38