等待线程完成OkHttp调用

时间:2019-01-13 15:34:38

标签: android api kotlin 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")
        }
    })
}

1 个答案:

答案 0 :(得分:1)

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

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