Android:改造:多个连续的异步请求。 Тoo许多嵌套项目
问题描述:
com.squareup.retrofit2:retrofit:2.3.0
我的步骤:Android:改造:多个连续的异步请求。 Тoo许多嵌套项目
- 开始异步请求:getCompaniesList()
- 等待成功响应
- 启动另一个异步请求:getCatalogsList()
- 等待成功响应
- 做一些其他的代码
这里摘录我的活动:
RestClient restClient = RestClientFactory.getRestClient();
Call<List<Company>> companyList = restClient.getCompaniesList(filters);
companyList.enqueue(new Callback<List<Company>>() {
@Override
public void onResponse(Call<List<Company>> call, Response<List<Company>> response) {
if (response.isSuccessful()) {
RestClient restClient = RestClientFactory.getRestClient();
Call<List<Catalog>> catalogList = restClient.getCatalogsList(filters);
catalogList.enqueue(new Callback<List<Catalog>>() {
@Override
public void onResponse(Call<List<Catalog>> call, Response<List<Catalog>> response) {
if (response.isSuccessful()) {
// HERE SOME NEED CODE!!!
}
}
@Override
public void onFailure(Call<List<Catalog>> call, Throwable throwable) {
}
});
}
}
@Override
public void onFailure(Call<List<Company>> call, Throwable throwable) {
}
});
我觉得这个结构不是很好。 Т多个嵌套物品。由于结果代码更复杂。
问题:这个结构有其他选择吗?
答
您可以花时间去学习的Rx RXjava2
,也可以分散你这样的代码
RestClient restClient = RestClientFactory.getRestClient();
Call<List<Company>> companyList = restClient.getCompaniesList(filters);
companyList.enqueue(getCompanyListCallback());
private Callback<List<Company>> getCompanyListCallback() {
return new Callback<List<Company>>() {
@Override
public void onResponse(Call<List<Company>> call, Response<List<Company>> response) {
if (response.isSuccessful()) {
RestClient restClient = RestClientFactory.getRestClient();
Call<List<Catalog>> catalogList = restClient.getCatalogsList(filters);
catalogList.enqueue(getCatalogsListCallback());
}
}
@Override
public void onFailure(Call<List<Company>> call, Throwable throwable) {
}
};
}
private Callback<List<Catalog>> getCatalogsListCallback() {
return new Callback<List<Catalog>>() {
@Override
public void onResponse(Call<List<Catalog>> call, Response<List<Catalog>> response) {
if (response.isSuccessful()) {
// HERE SOME NEED CODE!!!
}
}
@Override
public void onFailure(Call<List<Catalog>> call, Throwable throwable) {
}
};
}
+0
我认为将内部项目移动到单独的方法(getCatalogsListCallback()) - 是一个很好的解决方案。因为元素的嵌套总是= 1。现在代码很容易读取。 – Alexei
+0
如果这解决了您的问题,请upvote我的答案,并接受它作为您的问题的正确答案 – Boukharist
会建议使用'RxJava'这样的事情。 –
我在工作中遇到过同样的问题。更好看的代码的一个丑陋的解决方案将成功通知接口,并在每个接口中进行工作。但正如@约翰提到的,检查[RxJava](https://www.captechconsulting.com/blogs/getting-started-with-rxjava-and-android)或检查[Otto](http://square.github。 io/otto /)库 – riadrifai