【发布时间】: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