Retrofti 2
As you all might know, Retrofit can execute requests synchronously and Asynchronously.
Synchronous methods are executed on the main thread. That means the UI blocks during request execution and no interaction is possible for this period.
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.
In Retrofit2 if you want to execute requests synchronously:
Synchronous Requests
public interface TaskService {
@GET("/tasks")
Call<List<Task>> getTasks();
}
Get Results from Synchronous Requests
//service generator
TaskService taskService = ServiceGenerator.createService(TaskService.class);
Call<List<Task>> call = taskService.getTasks();
List<Task>> tasks = call.execute().body();
But if you want to execute the request asynchronously:
Asynchronous Requests
public interface TaskService {
@GET("/tasks")
Call<List<Task>> getTasks();
}
Get Results from Asynchronous Requests
//service generator
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());
}
}
As already mentioned above: the interface definition in Retrofit 2 is the same for synchronous and asynchronous requests. In the other words 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.
- Use
call.execute()
to run synchronously.
- Use
call.enqeue()
to run asynchronously.