Skip to content

Instantly share code, notes, and snippets.

@rezaiyan
Last active October 28, 2018 06:58
Show Gist options
  • Save rezaiyan/32c7c79bce7bd6ce019fa678262f6a25 to your computer and use it in GitHub Desktop.
Save rezaiyan/32c7c79bce7bd6ce019fa678262f6a25 to your computer and use it in GitHub Desktop.
It's an extension function to convert retrofit Call to a coroutine
suspend fun <T> Call<T>.await(): T = suspendCoroutine { continuation ->
enqueue(object : Callback<T> {
override fun onFailure(call: Call<T>, t: Throwable) {
continuation.resumeWithException(t)
}
override fun onResponse(call: Call<T>, response: Response<T>) {
if (response.isSuccessful)
continuation.resume(response.body()!!)
else
continuation.resumeWithException(HttpException(response)) // You can map the exception to anything you need
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment