首页 > 解决方案 > 等待线程完成 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")
        }
    })
}

标签: androidapikotlinokhttp

解决方案


在这种情况下,您应该使用前面提到的执行,并且由于 http 调用是异步处理的,因此您的线程是多余的,应该被删除。

如果要在所有请求完成后运行代码,一种方法是传入一个 onComplete 回调函数并计算完成的请求数,当所有线程完成时,调用包含应该是代码的回调函数在所有请求之后运行。


推荐阅读