我正在尝试使用 RxJava 实现 Retrofit。我已经获得了有关该主题的每个教程中显示的所有组件,但实际上我没有看到请求已启动。我错过了什么?将 Retrofit 转换为 RxJava 意味着没有 .enqueue()
可调用,那么为什么不发送请求?该应用程序具有互联网权限,我已经在模拟器和物理设备上对其进行了测试。我可以做些什么来进一步调试问题?
@GET("things/{thing}")
fun getThing(@Path("thing") thingName: String): Observable<Thing>
private val service: ThingsService
init {
val clientBuilder = OkHttpClient.Builder()
clientBuilder.addInterceptor(HttpLoggingInterceptor())
val retrofit = Retrofit.Builder()
.baseUrl("https://example.com")
.client(clientBuilder.build())
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava3CallAdapterFactory.create())
.build()
service = retrofit.create(ThingsService::class.java)
}
fun test(thingName) {
val aThing = service.getThing(thingName)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ thing -> }, { error -> })
}
使用此配置,我从未看到记录请求。
答案 0 :(得分:0)
看到绝对没有输出的问题是几个问题的组合:
当我测试在 .subscribe()
块中放置一条日志语句时,我没有在错误块中放置一条。
未正确设置 HttpLoggingInterceptor
上的日志级别以记录发生的错误类型。
在其中一个设备(模拟器)上,未正确授予 Internet 权限,因为该权限是在首次安装后添加到清单文件中的。
解决方案:
添加上网权限后卸载重装应用,检查错误块中的内容,并确保在拦截器中设置正确的日志级别:
val interceptor = HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY
}
val client = OkHttpClient.Builder().apply {
if (BuildConfig.DEBUG) {
addInterceptor(interceptor)
}
}.build()