简体   繁体   English

Retrofit 和 Rxjava 不发送请求

[英]Retrofit and Rxjava not sending request

I'm trying to implement Retrofit with RxJava.我正在尝试使用 RxJava 实现 Retrofit。 I've got all of the components shown in every tutorial I've found on the topic, but I don't actually see a request ever started.我已经找到了关于该主题的每个教程中显示的所有组件,但我实际上并没有看到任何请求开始。 What am I missing?我错过了什么? Converting Retrofit to RxJava means there is no .enqueue() to call, so why isn't the request sent?将 Retrofit 转换为 RxJava 意味着没有.enqueue()可以调用,那么为什么没有发送请求呢? The app has the internet permissions and I've tested it on both emulators and physical devices.该应用程序具有互联网权限,我已经在模拟器和物理设备上对其进行了测试。 What can I do to further debug the issue?我可以做些什么来进一步调试问题?

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

With this configuration I never see a request logged.使用此配置,我永远不会看到记录的请求。

The issue of seeing absolutely no output was a combination of several problems:绝对看不到 output 的问题是几个问题的组合:

  1. While I tested putting a log statement in the .subscribe() block, I didn't put one in the error block.当我测试在.subscribe()块中放置一条日志语句时,我没有在错误块中放置一条。

  2. The log level on the HttpLoggingInterceptor wasn't set correctly to log the type of error occurring. HttpLoggingInterceptor上的日志级别未正确设置以记录发生的错误类型。

  3. On one of the devices (the emulator) the internet permission hadn't been granted correctly because the permission was added to the manifest file after the first install.在其中一个设备(模拟器)上,未正确授予 Internet 权限,因为该权限是在首次安装后添加到清单文件中的。

Solution:解决方案:

Remove and reinstall the app after adding the internet permission, check for content in the error block, and be sure to set the correct log level in the interceptor:添加internet权限后删除并重新安装应用程序,检查错误块中的内容,并确保在拦截器中设置正确的日志级别:

val interceptor = HttpLoggingInterceptor().apply {
   level = HttpLoggingInterceptor.Level.BODY
}

val client = OkHttpClient.Builder().apply {
    if (BuildConfig.DEBUG) {
        addInterceptor(interceptor)
    }
}.build()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM