返回可观察
的改造界面interface WeatherApi {
companion object {
val HOST = "https://api.heweather.com/x3/"
val KEY = "41054a8f1d1a4ac992b1683e47a50146"
}
@GET("weather")
fun getWeather(@Query("city") city: String, @Query("key") key: String) : Observable<Weather>
}
RESTAPI:
class RestApi {
var weatherApi: WeatherApi
init {
val logInterceptor = HttpLoggingInterceptor()
logInterceptor.level = HttpLoggingInterceptor.Level.BODY
val okClient = OkHttpClient.Builder()
.addInterceptor(logInterceptor)
.retryOnConnectionFailure(true)
.connectTimeout(15, TimeUnit.SECONDS)
.build()
val retrofit = Retrofit.Builder()
.baseUrl(WeatherApi.HOST)
.addConverterFactory(JacksonConverterFactory.create(ObjectMapper().registerModule(KotlinModule())))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(okClient)
.build()
weatherApi = retrofit.create(WeatherApi::class.java)
}
fun getWeatherData(city: String, key: String): Observable<Weather> {
return weatherApi.getWeather(city, key)
}
消防代码:
restApi.getWeatherData("Qingdao", WeatherApi.KEY)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { t -> helloText?.text = t.data.first().basic.city }
当第一次调用firecode时,它将花费3秒钟 在主线程中反思事情,我很困惑,因为我已经习惯了 subscribeOn(Schedulers.io())。
我没有足够的声誉来发布图片,请参阅下面链接中的跟踪图片 http://ww2.sinaimg.cn/large/83f914a2jw1f6sn10bt2gj218g0p0qio.jpg
当我更改Retrofit界面以返回&#34; Call&#34;在RestApi中用Observable包装响应,事情就会正确。
返回致电
的改造界面interface WeatherApi {
companion object {
val HOST = "https://api.heweather.com/x3/"
val KEY = "41054a8f1d1a4ac992b1683e47a50146"
}
@GET("weather")
fun getWeather(@Query("city") city: String, @Query("key") key: String) : Call<Weather>
}
在RestApi中自己创建Observable:
fun getWeatherData(city: String, key: String): Observable<Weather> {
return Observable.fromCallable { weatherApi.getWeather("qingdao",WeatherApi.KEY).execute().body() }
}
然后调用fire代码,所有代价高昂的事情都将在Schedulers.io()线程中完成。
我没有足够的声誉来发布图片,请参阅下面链接中的跟踪图片 http://ww2.sinaimg.cn/large/83f914a2jw1f6smyi73xnj218g0p0dpk.jpg
我的问题是:
这辆车有问题吗?
为什么直接返回Observable会导致此错误?
或者我对Retrofit做了什么错误?