Skip to content

Instantly share code, notes, and snippets.

@osrl
Last active September 9, 2020 08:41
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save osrl/354159643e28cdb22cf0da786eadef37 to your computer and use it in GitHub Desktop.
Save osrl/354159643e28cdb22cf0da786eadef37 to your computer and use it in GitHub Desktop.
A Kotlin extension function to Retrofit Call class
inline fun <T> Call<T>.enqueue(crossinline onResult: Result<T>.() -> Unit) {
enqueue(object : Callback<T> {
override fun onFailure(call: Call<T>?, t: Throwable?) {
onResult(Result.Error(ApiError("Network error")))
}
override fun onResponse(call: Call<T>?, response: Response<T>) {
onResult(response.result())
}
})
}
fun <T> Response<T>.result(): Result<T> {
if (isSuccessful) {
val body = body()
return if (body != null) {
Result.Success(body)
} else {
Result.Error(ApiError("Empty body"))
}
}
return Result.Error(ApiError.from(errorBody()))
}
//this is inspired(!) from https://github.com/nickbutcher/plaid
sealed class Result<out T> {
data class Success<out T>(val data: T) : Result<T>()
data class Error(val error: ApiError) : Result<Nothing>()
override fun toString(): String {
return when (this) {
is Success<*> -> "Success[data=$data]"
is Error -> "Error[error=$error]"
}
}
}
api.getFoo()
.enqueue {
when(this) {
is Result.Success -> {
//use data
}
is Result.Error -> {
//use error
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment