2015-12-22 93 views
0

我使用Retrofit 2.0。为了充分利用REST类型的服务的一些数据我用的程序是这样的:改装取消请求

public Call downloadUser() { 
     // Create RetrofitService 
     Call<User> call = service.getUser(); 
     call.enqueue(new Callback<User>() { 
      @Override 
      public void onResponse(Response<User> response, Retrofit retrofit) { 
       // Do some operations with User obj if response.isSuccess() 
      } 

      @Override 
      public void onFailure(Throwable t) { 
       // Failure 
      } 
     }); 
     return call; 
    } 

在某些情况下,我要取消我的请求。我使用call.cancel(),但即使我将此过程称为Callback.onResponse(...)Callback.onFailure(...),因此使用Call.cancel()不会取消我的请求,并且它会一直持续到故障或响应。

回答

1

要知道一个通​​话是否被取消或者它是否真的成功,你需要两件事。

首先它看起来像Retrofit2的版本使用的是需要更新

您可以检查是否在通话是基于下面的代码取消。请注意,这将处理取消Call<>Dispatcher.class在OKHttp3

@Override 
public void onResponse(Response<User> response, Response response) { 
    if(response != null && response.isSuccessful()) { 
     //Do Stuff with the response 
    } 
} 

@Override 
public void onFailure(Call<User> user, Throwable t) { 
    if(user.isCanceled() || "Canceled".equals(t.getMessage())) { 
     //Call was canceled 
    } else { 
     //Call failed 
    } 
}