Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement an async Callback using Square's Retrofit networking library

As an iOS developer beginning to work with Android I came across Retrofit. I understand how to implement synchronous requests but am having trouble implementing asynchronous requests with success/failure callbacks. Specifically, the Callback syntax is unclear to me and there are no concrete examples of how to do this on the Retrofit website, the Square blogpost introducing Retrofit, or elsewhere that I've seen. Can someone please post some example code on this? I filed an issue in the Retrofit repo asking that they update the README with this info.

like image 971
Alfie Hanssen Avatar asked Jun 10 '13 23:06

Alfie Hanssen


People also ask

Does retrofit support synchronous or asynchronous calls?

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 performs and handles the method execution in a separated thread.

What is a callback in retrofit?

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.

What is asynchronous call in Android with example?

Asynchronous Call Example ( Recommended) Asynchronous calls should be made for non-blocking UI. In this way, android executes the request in a separate thread and does not block the main thread. It means the user can still interact with the app while waiting for the response.

What is call method in Retrofit 2?

Call.execute () and Call.enqueue () Methods In Retrofit 2, all requests are wrapped into a retrofit2.Call object. Each call yields its own HTTP request and response pair. Call interface provides two methods for making the HTTP requests: execute () – Synchronously send the request and return its response.


1 Answers

After some more research and just plain spending more time in the Android/Java world I figured this out, using the example from their docs.

Interface:

@GET("/user/{id}/photo")   void listUsers(@Path("id") int id, Callback<Photo> cb); 

Implementation:

RestAdapter restAdapter = new RestAdapter.Builder()             .setServer("baseURL")                  .build(); ClientInterface service = restAdapter.create(ClientInterface.class);  Callback callback = new Callback() {     @Override     public void success(Object o, Response response) {      }      @Override     public void failure(RetrofitError retrofitError) {      } }; service.listUsers(666, callback); 
like image 54
Alfie Hanssen Avatar answered Sep 24 '22 23:09

Alfie Hanssen