[英]Android: Custom Retrofit Callback, how can I prevent an implementation from doing its stuff
抱歉奇怪的標題不知道如何總結我的問題但我認為一旦我解釋代碼就會很清楚。
背景
如果沒有很多改進代碼,我會有一些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);
}
});
如果超級調用if語句為false,如何防止調用onResponse?
謝謝閱讀
您可以使用Fragment.isAdded()
來檢查片段當前是否已添加到其活動中。 你可以在這個Fragment.isAdded()上閱讀更多內容
您可以在執行請求時阻止接口,因此用戶無法導航回來。 為此,您可以顯示ProgressDialog。
示例代碼:
ProgressDialog progress = ProgressDialog.show(mContext, "dialog title",
"dialog message", false);
NetworkService.getListOfFood(new Callback<FoodList>() {
@Override
public void onResponse(Response<FoodList> response, Retrofit retrofit) {
if (response.isSuccess()) {
//Do Something cool
}
// Close the progress dialog when we obtain a response
progress.dismiss();
}
@Override
public void onFailure(Throwable t) {
// Handle the error
....
// Close the progress dialog when we obtain an error
progress.dismiss();
}
});
用戶必須等到請求完成
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.