Home > Net >  What the difference between using Call<T> object and suspend function in the retrofit?
What the difference between using Call<T> object and suspend function in the retrofit?

Time:01-29

I'm using Kotlin for the first time . I was able to make api calls in these 2 ways . What's the difference between them ?

With suspend function .

interface RetrofitInterface {
            @GET("/posts")
            suspend fun getUserData(): Response<List<User>>
        }

I will call my api with val result = apiCaller.getUserData()

Using Call<> object

interface RetrofitInterface {
    @GET("/posts")
    fun getUserDataWithCall(): Call<User>
    }

The api will be called via

val result2 = apiCaller.getUserDataWithCall().enqueue(object :Callback<User>{
        override fun onResponse(call: Call<User>, response: Response<User>) {}

        override fun onFailure(call: Call<User>, t: Throwable) {}
         })

CodePudding user response:

suspend is the coroutines keyword

CodePudding user response:

By using Call<> you are making the Retrofit request and response asynchronous - with call.enqueue . This is the best approach since network calls can take a while and block the Main Thread.

Without using Call<> :- In this case the network operation will execute on the Main thread which will lead to blocking the Main thread. so, in order to make the network call asynchronously we mark it as a suspend function to make it so if it is used in a coroutine synchronously the main thread will not be blocked.

  •  Tags:  
  • Related