Android - get response status code using retrofit and coroutines

Viewed 2768

I have a retrofit Service:

suspend fun getArticles(): Articles

and usually I can get response code in try/catch in a case of error.

try {
    val articles = service.getArticles()
} catch (e: Exception) {
    // I can get only codes different from 200...
}

But what if I need to distinguish between 200 and 202 codes for example and my service returns me only data object?

How to get response code if I have successful response?

1 Answers

Your interface would look like this

suspend fun getArticles(): Response<Articles>

then you use like this

val response = service.getArticles()
response.code() //gives you response code
val articles = response.body

or easier solution is

if (response.isSuccessful){ // Successful is any code between the range [200..300)
    val articles = response.body
}
Related