android - 等待线程完成 OkHttp 调用
问题描述
当我在另一个 OkHttp 调用中嵌套一个 OkHttp 调用时,我遇到了OkHttp的问题,我遇到了并发问题。在继续之前,我想等待我的内部调用完成其线程的工作。请看一下。
注意:我是 Kotlin 和多线程处理的新手。
private fun parseJson(url: String) {
val request = Request.Builder()
.url(url)
.build()
client.newCall(request).enqueue(object : Callback {
override fun onResponse(call: Call, response: Response?) {
var bodyOfProducts = response?.body()?.string()
var collectionJsonObject = jsonParseTool.fromJson(bodyOfProducts, Products::class.java)
val productsWithDetails = ArrayList<ProductDetails>()
for(product in collectionJsonObject.collects){
var concatProductUrl = "https://shopicruit.myshopify.com/admin/products.json?ids=" + product.product_id+ "&page=1&access_token=c32313df0d0ef512ca64d5b336a0d7c6"
val newRequest = Request.Builder()
.url(concatProductUrl)
.build()
val job = thread {
client.newCall(newRequest).enqueue(object : Callback {
override fun onResponse(call: Call, newResponse: Response?) {
var bodyOfProductDetails = newResponse?.body()?.string()
var productJsonObject = jsonParseTool.fromJson(bodyOfProductDetails, ProductDetails::class.java)
productsWithDetails.add(productJsonObject)
}
override fun onFailure(call: Call, e: IOException) {
println("EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE")
}
})
}
job.start()
job.join() // This should force my thread to finish before the rest of the code is executed on the main thread.
}
// println(collectionJsonObject.collects[0].product_id)
/*runOnUiThread {
recyclerViewCustomCollections.adapter = CollectionsAdapter(jsonObject)
}*/
}
override fun onFailure(call: Call, e: IOException) {
println("EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE")
}
})
}
解决方案
在这种情况下,您应该使用前面提到的执行,并且由于 http 调用是异步处理的,因此您的线程是多余的,应该被删除。
如果要在所有请求完成后运行代码,一种方法是传入一个 onComplete 回调函数并计算完成的请求数,当所有线程完成时,调用包含应该是代码的回调函数在所有请求之后运行。
推荐阅读
- javascript - 如何使用php获取select2的多个选定值
- vuejs2 - 为什么在站点加载时多次调用 nuxtServerInit
- android - 在 ListView Firebase 数据库中列出具有特定子值的用户
- r - 以矢量方式查找数据框行的邻居
- android - 如何在 android 中从 excel 中获取 20.67 美元的数据
- java - Thread 中的 join() 方法是否可以保证完美运行,或者它也依赖于单个 JVM?
- php - 带有标题修改的php curl
- php - 文本字段到文本视图
- angular6 - 如何在角度6的双引号内插入属性
- angularjs - 通过 Node JS 中的 URL 进行多个输入