因此,为了遵守责任分离原则,我试图让我的改造方法(listNearestAirports)将列表返回给演示者(在不同的包中)。但是我注意到改造很难,从必须在我的方法范围之外声明列表开始,到我只能在onResponse方法中遍历列表这一事实(当我尝试返回列表时,我获取空指针异常)。请参阅下面的代码:
public class NearestAirports {
List<GeoSearchResult> airportsList;
public List<GeoSearchResult> listNearestAirports(String lat, String lng) {
String reuquestBody = "{Escaped_JSON_request}";
AirportApi.Factory.getInstance().getAirports(requestBody).enqueue(new Callback<AirportCodes>() {
public void onResponse(Call<AirportCodes> call, Response<AirportCodes> response) {
airportsList = response.body().getGeoSearchRS().getGeoSearchResults().getGeoSearchResult();
//Here the list is populated successfully every time and I can iterate through it
System.out.println(airportsList.iterator().next().getCity());
}
public void onFailure(Call<AirportCodes> call, Throwable t) {
System.out.println("failed");
if (t instanceof IOException) {
System.out.println("actual network failure");
}
else {
System.out.println("conversion issue);
}
}
});
//Should return list, but at this point the list is null
return airportsList;
}
}
我想将列表返回给main(),所以我可以执行以下操作:
NearestAirports nearest = new NearestAirports();
airportsList = nearest.listNearestAirports(lat, lng);
System.out.println(airportsList.iterator().next().getCity());
for (GeoSearchResult airport : airportsList) {
System.out.print(airport.getId() + ", ");
System.out.println(airport.getName());
}
从改造中返回响应的最简单方法是什么? 我需要使用消毒吗?或者什么是将响应从处理和呈现响应中分离出来的最佳方法?
========================== *更新* =========== ==============
问题似乎与访问内部类有关
我试图在内部类之外声明一个变量,希望我可以为变量分配该变量。
失败的原因是:
1.我收到一条错误消息:variable accessed from an inner class must be declared final.
很好
2.我宣布它是最终的,但后来我收到另一条错误消息:this variable cannot be assigned because it's declared final.
这里讨论的一个技巧,对我的具体情况不起作用:
Local variable access to inner class needs to be declared final
我发现尝试将逻辑和改进响应从活动中分离出来很困难,因为最终我想在活动/片段中显示响应,并且它严重依赖于视图对象,在UI线程中执行等操作。
如何在不使用Rx java和Android的dataBinding ViewModel等的情况下为简单应用解决此问题?
答案 0 :(得分:2)
问题是您是否尝试使用异步代码实现同步行为。有人可能会争辩说,选择一种方法并始终如一地使用它会更好。
更具体,要么:
而不是使用Retrofit进行回调,而是同步执行网络调用,以便您可以立即处理响应:
// will be a vector with elements 2, 0 rather than a vector of size 2 with values 0, 0
std::vector<int> v{ 2, 0 };
initializer_list
,public class AirportApi {
public Call<AirportCodes> getAirports(@Body...);
}
public class NearestAirports {
public List<GeoSearchResult> listNearestAirports(String lat, String lng) {
final Response<AirportCodes> airportCodes = AirportApi.Factory.getInstance()
.getAirports(requestBody)
.execute();
// interrogate response and transform AirportCodes into List<GeoSearchResult>
// don't forget to account for failures
}
等)(作为示例...)更改API以返回RxJava Future
。然后从需要数据的点调用API并订阅调用调用的结果。
Single