Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call or Response in Retrofit?

I want to know the difference between Call And Response ? That when to use Call & when to use to Response in Retrofit ?

@GET("/albums/{id}")
suspend fun functionOne(@Path(value = "id") albumsId:Int):Response<Albums>
@GET("/albums/{id}")
suspend fun functionTwo(@Path(value = "id") albumsId:Int):Call<Albums>

These both functions works fine for me, both have different implementations but have almost same purposes.

1. What way of response type is good for best practices ?

2. When to use Response & Call ?

like image 462
Asim Zubair Avatar asked Sep 29 '20 17:09

Asim Zubair


2 Answers

"Call" is useful when we are willing to use its enqueue callback function.

 call.enqueue(new Callback<Info>() {
            @Override
            public void onResponse(Call<Info> call, Response<Info> response) {

                Info info = response.body();

                if (info != null && info.getRestResponse() != null) {

                    results = (ArrayList<Result>) info.getRestResponse().getResult();
                    viewData();
                }
            }

            @Override
            public void onFailure(Call<Info> call, Throwable t) {

            }
        });

When we use Coroutines or RxJava in the project(which is the best professional practice) to provide asynchronous execution , we don't need enqueue callback. We could just use Response.

suspend fun getMoviesFromAPI(): List<Movie> {
        lateinit var movieList: List<Movie>
        try {
            val response = movieRemoteDatasource.getMovies()
            val body = response.body()
            if(body!=null){
                movieList = body.movies
            }
        } catch (exception: Exception) {
            Log.i("MyTag", exception.message.toString())
        }
        return movieList
    }  
like image 145
AlexM Avatar answered Oct 14 '22 07:10

AlexM


1. What way of response type is good for best practices ?

I think it is depends on your use-case. By using retrofit2.Response<T>, we can access errorBody()(The raw response body of an unsuccessful response.), code()(HTTP status code.) or headers()(HTTP headers).

2. When to use Response & Call ?

  • Response: as above
  • Call: not necessary because callback type (such as Call) replaced by suspend function. Second method could be simpler like:
@GET("/albums/{id}")
suspend fun functionTwo(@Path(value = "id") albumsId:Int): Albums
like image 12
Petrus Nguyễn Thái Học Avatar answered Oct 14 '22 05:10

Petrus Nguyễn Thái Học