vchornenyi
vchornenyi

Reputation: 334

Cancel calls in retrofit:2.0.0-beta2 by tag

I use the com.squareup.retrofit:retrofit:2.0.0-beta2 and encounter some problem. I want to add the possibility to close some of the downloading by button press. So I found the cancel(Object tag) method in OkHTTPClient. I tried to find the place where I can put this tag value but didn't found anything. Also passing null as a parameter not work at all. Could someone help to tell me where I can put tag or suggest another approach?

Upvotes: 0

Views: 855

Answers (1)

Daniel
Daniel

Reputation: 2373

Retrofit2 has a cancel() method as well. You can use that. Here is an example:

Call<ResponseBody> call =
     downloadService.downloadFileWithDynamicUrlSync(fileUrl);
call.enqueue(new Callback<ResponseBody>() {  

     @Override
     public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
         Log.d(TAG, "request success");
     }

    @Override
    public void onFailure(Call<ResponseBody> call, Throwable t) {
        Log.e(TAG, "request failed");
    }
});
// something happened, for example: user clicked cancel button
call.cancel();

Be aware that if you cancel the request, Retrofit will classify it as a failure & call onFailure().

Further reading in case you're interested: https://futurestud.io/blog/retrofit-2-cancel-requests

Upvotes: 2

Related Questions