【问题标题】:How to call same API with different data, multiple times using retrofit?如何使用改造多次调用具有不同数据的相同 API?
【发布时间】:2020-08-17 19:10:00
【问题描述】:

场景是我正在使用类别 ID 加载产品。因此我做了一个for循环来多次调用API。

for (category in response.body()!!.categories) {
                        getProductByCategory(category)
                    }

问题是有时我会在 getProductByCategory API 中丢失数据,有时数据的顺序会发生变化。 我想要的是我的 API 在另一个之后被调用 1 但不是在前一个 API 完全执行之前。 限制是我不能使用.execute(),因为我希望我的 API 是异步的。

private fun getProductByCategory(category: CategoriesModel) {
    RetrofitClient.instance.productByCategory(category.id)
        .enqueue(object : Callback<ProductsInCategory> {
            override fun onResponse(
                call: Call<ProductsInCategory>,
                response: Response<ProductsInCategory>
            ) {
                //dialog.hide()
                //Log.e("TAG", "Product by Category Response: " + response.toString())
                if (response.body() != null) {
                    arrayProducts = response.body()!!.products
                    array.add(AllProductsModel(category, arrayProducts))
                    adapter.notifyDataSetChanged()
                }
            }

            override fun onFailure(call: Call<ProductsInCategory>, t: Throwable) {
                Toast.makeText(context, t.message, Toast.LENGTH_LONG).show()
                Log.e("TAG", "Failed Response: " + t.message)
                Log.e("TAG", "Failed Response Localized: " + t.localizedMessage)
                dialog.hide()
            }
        })
}

我不确定在这种情况下是否应该使用可运行线程或异步任务或任何其他涉及可观察的方法。

【问题讨论】:

  • 有什么解决办法吗?
  • 我不得不多次调用它!添加了多项检查没有正确的解决方案!

标签: android api kotlin retrofit retrofit2


【解决方案1】:
You can do something like this.

 list.forEach {
           coroutineScope { 
               async {  
                   
                       val result =   abcrepository.xyzapi(it)
                       when (result) {
                           is Result.Error -> {
                              
                           }
                           else -> {}
                       }
                   } else {
                      
                   }
               }.await()
           }
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-26
    • 2015-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多