Skip to content

Instantly share code, notes, and snippets.

@Ornolfr
Created February 18, 2019 08:17
Show Gist options
  • Save Ornolfr/d12b254f2fe38dbbb4fe75904c5f9359 to your computer and use it in GitHub Desktop.
Save Ornolfr/d12b254f2fe38dbbb4fe75904c5f9359 to your computer and use it in GitHub Desktop.
sealed class Result<T>
class SuccessfulResult<T>(val responseBody: T): Result<T>()
class UnsuccessfulResult<T>(val response: Response<T>?): Result<T>()
class ExceptionalResult<T>(val throwable: Throwable?): Result<T>()
suspend fun <T : Any> Call<T>.awaitResult(): Result<T> {
return suspendCancellableCoroutine { continuation ->
continuation.invokeOnCancellation {
cancel()
}
enqueue(object : Callback<T> {
override fun onResponse(call: Call<T>, response: Response<T>) {
val body = response.body()
continuation.resume(
if (response.isSuccessful && body != null)
SuccessfulResult(body)
else
UnsuccessfulResult(response)
)
}
override fun onFailure(call: Call<T>, t: Throwable) {
continuation.resume(ExceptionalResult(t))
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment