我正在尝试使用改造获得可观察的。我遇到了这个错误:
无法为rx. observable创建呼叫适配器。
这是我在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类,带有改造提供商
@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
Retrofit
中的支持是必须添加的插件,默认情况下不存在。
在您的build.gradle
中将此库添加到您的项目中:
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
并将Rx
适配器工厂提供给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();
}