Created
February 18, 2019 08:17
-
-
Save Ornolfr/d12b254f2fe38dbbb4fe75904c5f9359 to your computer and use it in GitHub Desktop.
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
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