CountDownLatch冻结Android上的线程

时间:2019-05-05 15:45:52

标签: android kotlin retrofit2 countdownlatch

我有一个方法,我想通过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

我使用任何错误的东西还是有其他方法来获得所需的功能?

1 个答案:

答案 0 :(得分:0)

翻新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()