Skip to content

Instantly share code, notes, and snippets.

@paulocns
Created August 26, 2018 02:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulocns/59ffa79281c6886400e42fb7f10a8649 to your computer and use it in GitHub Desktop.
Save paulocns/59ffa79281c6886400e42fb7f10a8649 to your computer and use it in GitHub Desktop.
public suspend fun <T : Any> Call<T>.await(): T {
return suspendCancellableCoroutine { continuation ->
enqueue(object : Callback<T> {
override fun onResponse(call: Call<T>?, response: Response<T?>) {
if (response.isSuccessful) {
val body = response.body()
if (body == null) {
continuation.resumeWithException(
NullPointerException("Response body is null: $response")
)
} else {
continuation.resume(body)
}
} else {
continuation.resumeWithException(HttpException(response))
}
}
override fun onFailure(call: Call<T>, t: Throwable) {
// Don't bother with resuming the continuation if it is already cancelled.
if (continuation.isCancelled) return
continuation.resumeWithException(t)
}
})
registerOnCompletion(continuation)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment