Skip to content

Instantly share code, notes, and snippets.

@rezaiyan
Created January 1, 2019 08:55
Show Gist options
  • Save rezaiyan/02d6ca51884d8985e493c4972452e24b to your computer and use it in GitHub Desktop.
Save rezaiyan/02d6ca51884d8985e493c4972452e24b to your computer and use it in GitHub Desktop.
package com.weembee.sdk.base
import retrofit2.HttpException
sealed class Result<out Any> {
data class Ok<T: Any>(val value: T): Result<T>()
data class NetworkError(val code: Int): Result<Nothing>()
data class Error(val throwable: Throwable): Result<Nothing>()
}
inline fun <T: Any> resultOrError(block: () -> T): Result<T> {
return try {
Result.Ok(block())
} catch (httpException: HttpException) {
Result.NetworkError(httpException.code())
} catch (throwable: Throwable) {
Result.Error(throwable)
}
}
package com.weembee.sdk.base
import retrofit2.Call
import retrofit2.Callback
import retrofit2.HttpException
import retrofit2.Response
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
private 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))
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment