Last active
October 28, 2018 06:58
-
-
Save rezaiyan/32c7c79bce7bd6ce019fa678262f6a25 to your computer and use it in GitHub Desktop.
It's an extension function to convert retrofit Call to a coroutine
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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