我使用retrofit2来处理Android应用程序的网络。我想抽象化网络,就像我只做netWorkManager.getsearch(),它做异步请求和UI更新一样。我见过的所有教程都有,在活动的代码中@Override onResponse的回调中更新UI的代码来更新UI (我想在我的networkManager中处理它)。我想传递一个函数或方法来处理回调的返回,但根据我的研究,我认为这并不是不可能的。我是不是在使用retrofit2时遗漏了什么?你有什么想法来解决我的问题吗?或者如何在Android中做一个很好的网络抽象?
发布于 2016-04-19 16:44:36
这绝对不是不可能的,尽管根据您使用的是同步(execute())调用还是异步(enqueue())调用而有所不同。
正如您从here中了解到的,这是您处理它们的方式:
Call<List<Car>> carsCall = carInterface.loadCars();
try {
Response<List<Car>> carsResponse = carsCall.execute();
} catch (IOException e) {
e.printStackTrace();
//network Exception is thrown here
}
if(carsResponse != null && !carsResponse.isSuccess() && carsReponse.errorBody() != null){
// handle carsResponse.errorBody()
} 对于异步呼叫:
Call<List<Car>> call = service.loadCars();
call.enqueue(new Callback<List<Car>>() {
@Override
public void onResponse(Response<List<Car>> response) {
// Get result from response.body(), headers, status codes, etc
}
@Override
public void onFailure(Throwable t) {
//handle error
}
});对于像这样定义的服务
public interface RetrofitCarService {
@GET("api/getCars")
Call<List<Car>> getCars();
}但是如果你想抽象化它,你可以很容易地做这样的事情
public interface YourCallback<T> {
void onSuccess(T t);
void onError(Throwable throwable);
}
public interface CarService {
void getCars(YourCallback<List<Car>> callback);
}
public class CarServiceImpl implements CarService {
private RetrofitCarService retrofitCarService;
public CarServiceImpl(RetrofitCarService retrofitCarService) {
this.retrofitCarService = retrofitCarService;
}
public void getCars(YourCallback<List<Car>> callback) {
retrofitCarService.getCars().enqueue(new Callback<List<Car>>() {
@Override
public void onResponse(Response<List<Car>> response) {
callback.onSuccess(response.body());
}
@Override
public void onFailure(Throwable t) {
callback.onError(t);
}
}
}
}然后你就会被抽象出来:
@Inject
CarService carService;
public void something() {
carService.getCars(new YourCallback<List<Car>>() {
public void onSuccess(List<Car> cars) {
refreshDataSet(cars);
}
public void onError(Throwable throwable) {
showError(throwable);
}
});
}请注意,这将迫使您的Service仅是异步的,这将丢弃Call同时表示同步和异步操作的能力。但是,如果您稍微考虑一下,也可以将Call<T>抽象出来。
https://stackoverflow.com/questions/36712746
复制相似问题