private val URL = http124931964510091 fun get url String msg String = method String = GET onSuccess String - Unit = val client = OkHttpClient var bo
可以使用Handler将client.newCall(request).enqueue部分包装起来。首先,在get函数中定义一个Handler对象:
val handler = Handler(Looper.getMainLooper())
然后,在onFailure和onResponse回调方法中,使用Handler将相应的操作包装起来:
override fun onFailure(call: Call, e: IOException) {
handler.post {
// 处理失败回调
}
}
override fun onResponse(call: Call, response: Response) {
val request = response.body?.string() ?: return
handler.post {
onSuccess.invoke(request)
}
}
这样,onFailure和onResponse回调方法中的操作就会在主线程中执行,可以直接更新UI或进行其他操作
原文地址: https://www.cveoy.top/t/topic/iknP 著作权归作者所有。请勿转载和采集!