Skip to content

Instantly share code, notes, and snippets.

@NikolayKul
Last active June 21, 2018 11:17
Show Gist options
  • Save NikolayKul/8284a6557cf47f2da752423094168353 to your computer and use it in GitHub Desktop.
Save NikolayKul/8284a6557cf47f2da752423094168353 to your computer and use it in GitHub Desktop.
An extension for Retorfit's Call<T> to wrap it into a suspended fun
suspend fun <T> Call<T>.await(): T = suspendCancellableCoroutine { cont ->
cont.invokeOnCompletion { cancel() }
enqueue(object : Callback<T> {
override fun onFailure(call: Call<T>, t: Throwable) {
cont.resumeWithException(t)
}
override fun onResponse(call: Call<T>, response: Response<T>) {
if (response.isSuccessful) {
cont.resume(response.body()!!)
} else {
cont.resumeWithException(HttpException(response))
}
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment