com.squareup.retrofit2:retrofit:2.3.0
我的步骤:
我的活动中的代码段:
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) {
}
});
我觉得这个结构不是很好。 Тoo许多嵌套项目。结果代码更复杂。
问题:有这种结构的替代方案吗?
答案 0 :(得分:1)
您可以花时间学习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) {
}
};
}