Retrofit — Synchronous and Asynchronous Requests
Within the previously published tutorials, we walked you through the setup of Retrofit. This tutorial shows you how to perform the actual requests in either a synchronous or a asynchronous way.
Retrofit Series Overview
- Getting Started and Creating an Android Client
- Basics of API Description
- Creating a Sustainable Android Client
- URL Handling, Resolution and Parsing
- How to Change API Base Url at Runtime
- Multiple Server Environments (Develop, Staging, Production)
- Share OkHttp Client and Converters between Retrofit Instances
- Upgrade Guide from 1.9
- Beyond Android: Retrofit for Java Projects
- How to use OkHttp 3 with Retrofit 1
- Synchronous and Asynchronous Requests
- Send Objects in Request Body
- Add Custom Request Header
- Manage Request Headers in OkHttp Interceptor
- Dynamic Request Headers with @HeaderMap
- Multiple Query Parameters of Same Name
- Optional Query Parameters
- Send Data Form-Urlencoded
- Send Data Form-Urlencoded Using FieldMap
- How to Add Query Parameters to Every Request
- Add Multiple Query Parameter With QueryMap
- How to Use Dynamic Urls for Requests
- Constant, Default and Logic Values for POST and PUT Requests
- Cancel Requests
- Reuse and Analyze Requests
- Optional Path Parameters
- How to Send Plain Text Request Body
- Customize Network Timeouts
- How to Trust Unsafe SSL certificates (Self-signed, Expired)
- Dynamic Endpoint-Dependent Interceptor Actions
- How to Update Objects on the Server (PUT vs. PATCH)
- How to Delete Objects on the Server
- Introduction to (Multiple) Converters
- Adding & Customizing the Gson Converter
- Implementing Custom Converters
- How to Integrate XML Converter
- Access Mapped Objects and Raw Response Payload
- Supporting JSON and XML Responses Concurrently
- Handling of Empty Server Responses with Custom Converter
- Send JSON Requests and Receive XML Responses (or vice versa)
- Unwrapping Envelope Responses with Custom Converter
- Wrapping Requests in Envelope with Custom Converter
- Define a Custom Response Converter
TL;DR
Retrofit supports synchronous and asynchronous request execution. Users define the concrete execution by setting a return type (synchronous) or not (asynchronous) to service methods.
Synchronous Requests
Synchronous requests with Retrofit 1.9 are declared by defining a return type. The example below expects a list of tasks as the response when executing the method getTasks
.
Retrofit 2
public interface TaskService {
@GET("/tasks")
Call<List<Task>> getTasks();
}
Retrofit 1.9
public interface TaskService {
@GET("/tasks")
List<Task> getTasks();
}
Within Retrofit 2, every request is wrapped into a Call
object. The actual synchronous or asynchronous request is executed differently using the desired method on a later created call
object. However, the interface definition for synchronous and asynchronous requests are the same within Retrofit 2.
Synchronous methods are executed on the main thread. That means the UI blocks during request execution and no interaction is possible for this period.
Synchronous methods provide the ability to use the return value directly, because the operation blocks everything else during your network request.
For non-blocking UI, you have to handle the request execution in a separated thread by yourself. That means, you can still interact with the app itself while waiting for the response.
Get Results from Synchronous Requests
Let’s move to the point where we execute the actual request. This behavior changed from Retrofit v1 to v2. The following code snippets illustrate the synchronous request execution with Retrofit and assume that you’re familiar with the ServiceGenerator
class introduced in the tutorial on how to create a sustainable Android client.
Retrofit 2
TaskService taskService = ServiceGenerator.createService(TaskService.class);
Call<List<Task>> call = taskService.getTasks();
List<Task>> tasks = call.execute().body();
Retrofit 1.9
TaskService taskService = ServiceGenerator.createService(TaskService.class);
List<Task> tasks = taskService.getTasks();
Using the .execute()
method on a call
object will perform the synchronous request in Retrofit 2. The deserialized response body is available via the .body()
method on the response object.
Asynchronous Requests
Additionally to synchronous calls, Retrofit supports asynchronous requests out of the box. Asynchronous requests in Retrofit 1.9 don’t have a return type. Instead, the defined method requires a typed callback as last method parameter.
Retrofit 2
public interface TaskService {
@GET("/tasks")
Call<List<Task>> getTasks();
}
Retrofit 1.9
public interface TaskService {
@GET("/tasks")
void getTasks(Callback<List<Task>> cb);
}
Retrofit performs and handles the method execution in a separated thread. The Callback
class is generic and maps your defined return type. Our example returns a list of tasks and the Callback does the mapping internally.
As already mentioned above: the interface definition in Retrofit 2 is the same for synchronous and asynchronous requests. The desired return type is encapsulated into a Call
object and the actual request execution defines its type (synchronous/asynchronous).
Get Results from Asynchronous Requests
Using asynchronous requests forces you to implement a Callback
with its two callback methods: success
and failure
. When calling the asynchronous getTasks()
method from a service class, you have to implement a new Callback
and define what should be done once the request finishes. The following code snippet illustrates an exemplary implementation.
Retrofit 2
TaskService taskService = ServiceGenerator.createService(TaskService.class);
Call<List<Task>> call = taskService.getTasks();
call.enqueue(new Callback<List<Task>>() {
@Override
public void onResponse(Call<List<Task>> call, Response<List<Task>> response) {
if (response.isSuccessful()) {
// tasks available
} else {
// error response, no access to resource?
}
}
@Override
public void onFailure(Call<List<Task>> call, Throwable t) {
// something went completely south (like no internet connection)
Log.d("Error", t.getMessage());
}
}
Retrofit 1.9
TaskService taskService = ServiceGenerator.createService(TaskService.class);
taskService.getTasks(new Callback<List<Task>>() {
@Override
public void success(List<Task> tasks, Response response) {
// here you do stuff with returned tasks
}
@Override
public void failure(RetrofitError error) {
// you should handle errors, too
}
});
Get Raw HTTP Response
In case you need the raw HTTP response object, just define it as the method’s return type. The Response
class applies to both methods like any other class.
Retrofit 2
The way you can receive the raw response body in Retrofit 2 has change to v1 the same way you define the request type (sync/async). Namely, you don’t need to define the Response
class as the return type, but you can grab it within the onResponse()
callback method. Let’s look at the following code snippet to illustrate how you can get the raw response:
call.enqueue(new Callback<List<Task>>() {
@Override
public void onResponse(Call<List<Task>> call, Response<List<Task>> response) {
// get raw response
Response raw = response.raw();
}
@Override
public void onFailure(Call<List<Task>> call, Throwable t) {}
}
Retrofit 1.9
// synchronous
@GET("/tasks")
Response getTasks();
// asynchronous
@GET("/tasks")
void getTasks(Callback<Response> cb);
Happy coding! If you run into problems or need help, please find us on Twitter @futurestud_io.
Additional Resources
- Retrofit API declaration, section synchronous vs. asynchronous vs. observable