gpt4 book ai didi

java - Android:Custom Retrofit Callback,我怎样才能阻止实现做它的事情

转载 作者:太空狗 更新时间:2023-10-29 15:26:13 26 4
gpt4 key购买 nike

抱歉标题很奇怪,不确定如何总结我的问题,但我认为一旦我解释了代码就会清楚。

背景

在没有放入大量改造代码的情况下,我有一些 API 调用是这样的

 public static void getListOfFood(@NonNull Callback<FoodList> callback) {
Call<FoodList> call = RetrofitClient.get().getFood();
call.enqueue(callback);
}

在我 fragment 的某个地方我有这个

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) {
}
});

所以我遇到的问题是,假设这个 fragment 已经被销毁(用户导航回来),响应仍然被传递并且我得到空指针,因为它正在调用 onResponse grrrrr 中的代码!

核心问题

fragment 有一个叫做 isRemoving 的方法,它是 fragment 是否被删除的指示器,所以我可以用 if 语句包装 onResponse 和 onFailure,但是当有许多其他请求时它会变得困惑

我的解决方案和需要帮助的问题

我做了一个实现调用的抽象类

 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) {

}
}

然后在我的 fragment 中我创建了一个实现并调用 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 call if 语句为 false,如何防止调用 onResponse 实现?

感谢阅读

最佳答案

您可以使用 Fragment.isAdded() 来检查该 fragment 当前是否已添加到其 Activity 中。您可以阅读更多关于此的信息 Fragment.isAdded()

关于java - Android:Custom Retrofit Callback,我怎样才能阻止实现做它的事情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32910343/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com