Android Retrofit - Callback vs no call back

6.7k views Asked by At

I am analyzing retrofit on android and had a question on callbacks vs not using them. I am under the impression that callbacks are only used for success and failure responses a client might desire. Otherwise i would omit it. Here is an example of a retrofit interface without a callback:

 public interface GitHubService {
  @GET("/users/{user}/repos")
  List<Repo> listRepos(@Path("user") String user);
}

and here is an example with a callback (i hope i have it right):

   public interface GitHubService {
  @GET("/users/{user}/repos")
  List<Repo> listRepos(@Path("user") String user,Callback<Repo> cb);
}

Im confused on two things:

  1. The return value in the interface is List but to me it should be void because retrofit will use gson to convert the json response to a Repo POJO. All i have to do is create the Repo POJO so i would expect the last piece of code to be like this instead:

    public interface GitHubService {

    @GET("/users/{user}/repos")

    void listRepos(@Path("user") String user,Callback cb); }

What is the purpose of the return value?

  1. my second question is : is the callback only necessary to know if the request was a success or failure as i see from the docs that callback has two methods: failure and success.
1

There are 1 answers

4
reidzeibel On BEST ANSWER

I want to try and answer your question

1. You are correct, the return value should be void, as you will get the response from the Callback

2. Yes it is, the Callback is needed to check whether the request is successful or not, also it is there to grab the server response.

Hope this is useful, cheers!


EDIT : You can use direct return value or use callbacks to get the response. Quoting from the retrofit documentation site :

  • A method with a return type will be executed synchronously.
  • Asynchronous execution requires the last parameter of the method be a Callback.

So I guess the documentation answers it really, Callback is needed if you want the execution to be asynchronous :D