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 ?
"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
}
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).
Call
) replaced by suspend function
. Second method could be simpler like:@GET("/albums/{id}")
suspend fun functionTwo(@Path(value = "id") albumsId:Int): Albums
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