代码之家  ›  专栏  ›  技术社区  ›  Naman Jain

等待线程完成OKHTTP调用

  •  0
  • Naman Jain  · 技术社区  · 6 年前

    我一直有问题 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 回复  |  直到 6 年前
        1
  •  1
  •   Patrick    6 年前

    在这种情况下,您应该像前面提到的那样使用execute,因为HTTP调用是异步处理的,所以您的线程是多余的,应该删除。

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