Ma2340
Ma2340

Reputation: 727

Conceptual question regarding suspend and Deferred

I have a question about when to use suspend and when not. My APIRepo class has a function like this -

override suspend fun retrieveDataFromRemote(): MyResult {
        if (utility.checkDeviceInternetConnection()) {
            try {
                val result = remoteInterface.getData().await()
                return ...
            } catch (t: Throwable) {
                return ...
            }
        } else {
            return ...
        }
    }

My Remote interface code looks like this -

@GET("/data/mydata")
fun getData(): Deferred<Response<MyModel>>

As you can see my RemoteInterface has no suspend keyword and returns a Deferred. This works totally fine. But when I add a suspend keyword to getData(), then I dont get the API response. Why is it like that? Does it have something to do with the Deferred?

Upvotes: 1

Views: 270

Answers (2)

Fartab
Fartab

Reputation: 5493

Retrofit 2.6.0 or newer has built-in suspend support.

Probably you are using Kotlin Coroutine Adapter. This library depends on reflection to detect whether the return type is Deffered or not. See here.

Here is an example using Retrofit 2.6.0 :

interface RemoteInterface{

  @GET("/data/mydata")
  suspend fun getData(): MyModel
}

And in your ViewModel:

fun retrieveDataFromRemote() {
  viewModelScope.launch {
      val model = remoteInterface.getData()
      // do something with model
  }
}

Upvotes: 1

Cuong Nguyen
Cuong Nguyen

Reputation: 1018

  • When to use suspend and when not? You can refer to suspend

  • From Retrofit 2.6.0 or newer and it's built-in suspend support, not use Deferred

Upvotes: 0

Related Questions