Is there a neater way to do this?
# announcements
t
Is there a neater way to do this?
Copy code
override fun onResponse(call: Call, response: Response) {
    if (response.isSuccessful) {
        response.body?.let { body ->
            continuation.resume(body.byteStream())
        } ?: continuation.resumeWithException(IOException("Request failed: $response"))
    } else {
        continuation.resumeWithException(IOException("Request failed: $response"))
    }
}
My first thought was:
Copy code
override fun onResponse(call: Call, response: Response) {
    if (response.isSuccessful) {
        response.body?.let { body ->
            continuation.resume(body.byteStream())
            return@let
        }
    }

    continuation.resumeWithException(IOException("Request failed: $response"))
}
But the 'early return' doesn't actually exit the outer scope
Oh, I'm a dumbass.
Just need to
return
instead of
return@let
. Confused myself trying to solve a problem I didn't have
­čĄ» 1
rubber duck 1
y
You can also do
if(response.isSuccessful && response.body != null) { //resume with stream } else //resume with exception
Alternatively, you could also make a body property that returns null if the response wasn't successful i.e. like this:
Copy code
val Response.successfulBody get() = if(response.isSuccesful) response.body else null
and then:
Copy code
override fun onResponse(call: Call, response: Response) {
    response.successfulBody?.let { body ->
        continuation.resume(body.byteStream())
    } ?: continuation.resumeWithException(IOException("Request failed: $response"))
}
or even turn it into a one-liner if you want:
Copy code
override fun onResponse(call: Call, response: Response) = response.successfulBody?.let { continuation.resume(it.byteStream()) } ?: continuation.resumeWithException(IOException("Request failed: $response"))