Search code examples
androidkotlinretrofitretrofit2

Confusion about the use of Call<> and suspended functions in Android network requests with retrofit


After searching for answers to an error where my function fun getRestaurants(): Call couldn't be made suspended, I found at this question that you can't combine a suspended function with a Call<> return, and my problem was solved. However, I still don't fully understand when to use Call<> and when to suspend the function, at least in this context where I am making @GET and @POST requests to the API, as I understand there is an input and output of data, so it is better to work with a suspended function, but then what is the purpose of Call in this situation.

interface RestaurantsApiService {
@GET("restaurants?populate=*")
fun getRestaurants(): Call<Restaurants>
}

or

interface RestaurantsApiService {
@GET("restaurants?populate=*")
suspend fun getRestaurants(): Restaurants
}

Currently, in my application, I am using Call because the book I am learning from does, and although it later changes Call to a suspended function, it doesn't really explain why or what the benefit of doing so is.

I know and understand why to use and how to handle coroutines, which I can do when I call getRestaurants() inside another function/val etc, but my doubt is precisely at getRestaurants().


Solution

  • Call is for when you’re not using coroutines at all. Mostly it would be used in pure Java projects. It doesn’t make sense to use it if you’re using coroutines unless you’re working on a legacy project where there are some modules not using coroutines yet. Then you can use Call and inside a coroutine you would call await() on it to get the result in a suspending, synchronous way.