【发布时间】:2015-10-03 01:04:16
【问题描述】:
对不起,奇怪的标题不知道如何总结我的问题,但我认为一旦我解释了代码就会清楚。
背景
在没有放入大量改造代码的情况下,我有一些类似这样的 API 调用
public static void getListOfFood(@NonNull Callback<FoodList> callback) {
Call<FoodList> call = RetrofitClient.get().getFood();
call.enqueue(callback);
}
在我的片段中的某个地方我有这个
NetworkService.getListOfFood(new Callback<FoodList>() {
@Override
public void onResponse(Response<FoodList> response, Retrofit retrofit) {
if (response.isSuccess()) {
//Do Something cool
}
}
@Override
public void onFailure(Throwable t) {
}
});
所以我遇到的问题是,假设这个片段已被破坏(用户导航回来),响应仍然被传递,我得到空指针,因为它正在调用 onResponse grrrrr 中的代码!
核心问题
片段有一个称为 isRemoving 的方法,它指示片段是否被删除,因此我可以用 if 语句包装 onResponse 和 onFailure 但当有许多其他请求时它会变得混乱
我需要帮助的解决方案和问题
我创建了一个实现 Call 的抽象类
public abstract class MyCustomCallback<T> implements Callback<T> {
private WeakReference<Fragment> mWeakFragment;
public MyCustomCallback(Fragment fragment){
this.mWeakFragment = new WeakReference<>(fragment);
}
@Override
public void onResponse(Response<T> response, Retrofit retrofit) {
Fragment fragment = mWeakFragment.get();
if(fragment != null && !fragment.isRemoving()){
return;
}else{
return;
}
}
@Override
public void onFailure(Throwable t) {
}
}
然后在我的片段中,我创建了一个实现并调用 super
NetworkService.getListOfFood(new MyCustomCallbackk<FoodList>(this) {
@Override
public void onResponse(Response<FoodList> response, Retrofit retrofit) {
super.onResponse(response, retrofit);
if (response.isSuccess()) {
}
}
@Override
public void onFailure(Throwable t) {
super.onFailure(t);
}
});
如果 super 调用 if 语句为 false,如何防止调用实现 onResponse?
感谢阅读
【问题讨论】:
-
找到任何解决方案了吗?