Near1999
Near1999

Reputation: 1607

Retrofit cancel request

I'm using Retrofit 2.0. To get some data from RESTFull services I use procedures like this:

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

In some cases, I need to cancel my request. I use call.cancel(), but even if I call this procedure Callback.onResponse(...) or Callback.onFailure(...) triggered anyway, so using Call.cancel() doesn't cancel my request and it keeps on going until failure or response.

Upvotes: 0

Views: 1427

Answers (1)

Matthew
Matthew

Reputation: 3431

To know if a call was canceled or if it was truly successful you'll need to two a few things.

First it looks like the version of Retrofit2 you are using needs to be updated

Second you can check if a call was canceled based on the code below. Note that this will deal with cancels from the Call<> or the Dispatcher.class in 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 
    }
}

Upvotes: 1

Related Questions