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.
Asked
Active
Viewed 2.9k times
28
1 Answers
54
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);

Alfie Hanssen
- 16,964
- 12
- 68
- 74
-
3Don't forget to call setExecutors() when creating your restAdapter. – SeanPONeil Jul 15 '13 at 14:03
-
4@SeanPONeil you only need to setExecutors() when you want the callback to happen off the main thread too. – gkee Aug 08 '13 at 09:34
-
Not at the time when I posted that. Square added sane defaults for the executors. – SeanPONeil Aug 08 '13 at 19:58
-
2@Alfie Hanssen : I have a noob query for retrofit. In the success method, what's the difference between o and Response ? Which one should I use for getting say, JSON data sent from the server ? – dev Feb 08 '14 at 23:40
-
1@Raj 'o' is the request object, 'response' is the actual result. You would get the JSON data from the 'response' object. – bitbandit Apr 16 '14 at 08:32
-
@StormeHawke obviously I did, no one responded. So it was a kind of desperate move. Anyways I did solve the issues eventually. – ShahrozKhan91 Sep 09 '14 at 05:41
-
7I still exactly dont get How to implement Retrofit callback – geniushkg Mar 02 '15 at 06:21
-
1With refrofit 2.0 there is no RestAdapter anymore. – Vlado Pandžić Aug 30 '15 at 17:17
-
Look at [this answer](http://stackoverflow.com/a/32614103/192961) for the Retrofit 2.0 way of dealing with callbacks. – Koen Apr 13 '17 at 11:09