Last active
June 21, 2018 11:17
-
-
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
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 = 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