andreluizreis
11/27/2017 - 10:44 PM

Retrofit Synchronous and Asynchronous calls

[Retrofit Synchronous and Asynchronous calls] #android

// Retrofit Synchronous and Asynchronous calls
// From: https://futurestud.io/tutorials/retrofit-synchronous-and-asynchronous-requests
// #android

// Synchronous 
TaskService taskService = ServiceGenerator.createService(TaskService.class);  
Call<List<Task>> call = taskService.getTasks();  
List<Task>> tasks = call.execute().body(); 

// ========

// Asynchronous 
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());
    }
}