Retrofit 2.0: Cancelling Call Objects
Understanding Call Objects
In Retrofit, the Call
object represents an asynchronous request. It holds the details of the HTTP request and allows you to execute it and receive a response. Sometimes, you might need to cancel an ongoing request, for example, when:
- The user navigates away from the screen.
- A new request is triggered, making the previous one obsolete.
- An error occurs that prevents the request from completing.
Cancellation Methods
Retrofit provides two primary ways to cancel a Call
object:
1. The cancel()
Method
The cancel()
method is the most straightforward way to cancel a request. It immediately stops the request and releases any resources associated with it.
Call call = apiService.getData();
// ...
call.cancel();
2. The enqueue()
Method
When using the enqueue()
method, you provide a Callback
object. The Callback
object’s onCancelled()
method is invoked when the request is cancelled.
Call call = apiService.getData();
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
// Handle response
}
@Override
public void onFailure(Call call, Throwable t) {
// Handle failure
}
@Override
public void onCancelled(Call call) {
// Handle cancellation
}
});
Managing Cancellation in a Practical Example
Let’s demonstrate cancellation with a simple example:
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;
// Interface defining the API endpoint
public interface ApiService {
@GET("/data")
Call getData();
}
public class Main {
public static void main(String[] args) {
// Create a Retrofit instance
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.example.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
// Create an instance of the API service
ApiService apiService = retrofit.create(ApiService.class);
// Initiate a request
Call call = apiService.getData();
// ... Perform some operation
// Cancel the request
call.cancel();
}
}
Considerations
- **Cancellation is Best Effort:** While Retrofit does its best to cancel requests, the actual cancellation might be delayed depending on the network state and server-side implementation.
- **Resource Release:** When a request is cancelled, it’s essential to release resources properly, including closing input streams and network connections.
- **Response Handling:** If the cancellation occurs before the response is received, the
onCancelled()
method in yourCallback
will be invoked. However, if the response is already received, theonResponse()
method will be called. Handle these situations appropriately to avoid potential issues.