使用 Kotlin 协程包装 enqueue() 时, 总是会发生java.lang.ClassCastException: java.lang.Object cannot be cast to okhttp3.Response
这样的异常. 通过调试也没搞明白原因.
下面是正确的简单用例:
suspendCoroutine<Int> {co -> co.resume(1)} // ok
suspendCoroutine<Int> {co -> co.resumeWithException(NullPointerException())} // ok
下面是发生错误的用例:
val http = OkHttpClient.Builder().build()
val appid = "mock"
val secret = "mock"
val code = "mock"
val api = "https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code"
val request = Request.Builder().get().url(api).build()
val cc =
runBlocking {
val resp = suspendCoroutine<Response> { co ->
http.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
co.resumeWithException(e)
}
override fun onResponse(call: Call, response: Response) {
// 此处 response 是正确的.
co.resume(response)
}
})
}
// Exception in thread "main" java.lang.ClassCastException: java.lang.Object cannot be cast to okhttp3.Response
println(resp.body()?.string())
resp
}
}
不清楚但
http.newCall(request).enqueue(object : Callback)
已经是异步调用了。--- 补充
可以参考如何用Kotlin Coroutines和Architecture Components进行Android开发?,学习Kotlin Coroutines。