Conclusion | raywenderlich.com


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/10376651-android-networking-fundamentals/lessons/30

Hi.
when I used “call” I could get the response code from the body, but now with this new way using suspension functions and the response object directly as a return, How do I get the response codes? 200,300,400, etc.

Hey @ricindigus!

I mentioned this in the course, but basically, when you use suspend, you get the data immediatelly, or the call fails, throwing an exception.

This is why you have the try/catch block. And then you can, in the catch block, use the exception/throwable, to get the error code.

You don’t need to check if there’s a 200 code, if you get into the success case (within try), and you can check for any other code that’s an error, within the catch.

Hi yeah i did that
handle the throwable in other function for all.
I already found the solution.

suspend fun <T: Any> safeApiCall(dispatcher: CoroutineDispatcher, apiCall: suspend () -> T): Result<T> {
return withContext(dispatcher) {
    try {
        Success(apiCall.invoke())
    } catch (throwable: Throwable) {
        when (throwable) {
            is IOException -> Failure(null,null)
            is HttpException -> {
                val code = throwable.code()
                val errorResponse = convertErrorBody(throwable)
                Failure(code, errorResponse)
            }
            else -> {
                Failure(null, null)
            }
        }
    }
}
}

Now I have another question: Since the service is called and I get the response object directly. How would you do if the answer is just a 200 with no answer body? Use Void? or ResponseBody? as return parameter? Or did I indicate the response parameter ?:

for example this service only responds with code 200 with an empty response body, how would it be the correct way to write it?:

@POST("/v1/tokens-sms/token-sms/validate")
fun saveSmsCode(@Body validateTokenRequest: ValidateTokenRequest):ResponseBody

or

@POST("/v1/tokens-sms/token-sms/validate")
fun saveSmsCode(@Body validateTokenRequest: ValidateTokenRequest):Void

or just

@POST("/v1/tokens-sms/token-sms/validate")
fun saveSmsCode(@Body validateTokenRequest: ValidateTokenRequest)

Hey there @ricindigus!

I would personally always try to return values from API functions, unless there is absolutely no UI change/update you need to show the user.

So if the user needs to see an error if something goes wrong, or a message/prompt/popup if something goes right , then I’d say return a response body, and in turn either a Success or a Failure of a case.

Hope that helps!

1 Like