【问题标题】:CountDownLatch freezes thread on AndroidCountDownLatch 冻结 Android 上的线程
【发布时间】:2019-05-05 15:45:52
【问题描述】:

我有一个方法,我想通过 Retrofit 的 API 调用检查我的令牌的有效性,我想等待结果。我想使用 CountDownLatch 但似乎countDownLatch.await() 锁定了线程并且没有任何反应,调试器没有到达onResponse 部分。我用 Postman 检查了我的 API,调用确实成功了。

我还发现这个问题与我的问题类似,但没有帮助: CountDownLatch not freeing thread

    var isTokenExpired = false

    var countDownLatch = CountDownLatch(1)

    val userService = RetrofitClient.getInstance().create(DiaBUserService::class.java)
    userService.validate(token).enqueue(object : Callback<JsonObject> {
        override fun onResponse(call: Call<JsonObject>, response: Response<JsonObject>) {
            isTokenExpired = !response.isSuccessful
            countDownLatch.countDown()
        }

        override fun onFailure(call: Call<JsonObject>, t: Throwable) {
            t.printStackTrace()
            countDownLatch.countDown()
        }
    })

    try {
        countDownLatch.await()
    } catch (e: InterruptedException){
        e.printStackTrace()
    }

    return isTokenExpired

是我用错了什么还是有其他方法可以得到想要的功能?

【问题讨论】:

    标签: android kotlin retrofit2 countdownlatch


    【解决方案1】:

    改造Callback 文档说:

    Callbacks are executed on the application's main (UI) thread.
    

    主线程被方法CountDownLatch#await阻塞,所以CountDownLatch#countDown不会被执行。您可以为要运行的回调指定一个后台执行程序(例如SingleThreadExecutor)。

    val retrofit = Retrofit.Builder()
            // options
            .callbackExecutor(Executors.newSingleThreadExecutor())
            // options
            .build()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-22
      • 2019-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多