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.
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.
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With