IAmNotARobot
IAmNotARobot

Reputation: 1445

Retrofit 2.X - Response vs Call - What is the recommended to use?

Please can you explain to me the difference of "Call" and "Response" in retrofit 2.X, What is the recommended way to use? and the difference of each. For instance I want to consume a 4 API calls with coroutines at the same time some might wait for response of other API and some will not. Thank you.

Upvotes: 3

Views: 2567

Answers (2)

Mohamad Seyedi
Mohamad Seyedi

Reputation: 443

Call --> When you wanna use request callback for error or response, you can use that. it's useful for tracking request status if it is successful or failed.

call.enqueue(object : Callback<T> {
     override fun onResponse(call: Call<T>, response: Response<T>) {
         // in response
     }
    
     override fun onFailure(call: Call<T>, t: Throwable) {
         // in error
     }
})

Response --> When you wanna use kotlin Coroutines or RxJava in your project, it's strongly recommended to use Response. It's very very fantastic experience to use that for working with asynchronous tasks...

suspend fun getUsersFromServer(): List<User> {
    var users = ArrayList<User>()
    val response = retrofitService.getUsers()
    response.body()?.let {
        users = it
    }
    return users
}

Upvotes: 0

ChristianB
ChristianB

Reputation: 2690

They are types for different purposes, but they come hand in hand.

Call<T> is a container that "sends a request to a webserver and returns a response".

Response is a container that delivers a result back to you, either from calling enqueue(Callback<T> callback) (asynchronously) and implementing Callback<T> or by calling execute() (synchronously). A Response can be either successful or a failure.

In other words, first you do a Call and then you get back a Response.

Documentation

Upvotes: 1

Related Questions