Last active
September 9, 2020 08:41
-
-
Save osrl/354159643e28cdb22cf0da786eadef37 to your computer and use it in GitHub Desktop.
A Kotlin extension function to Retrofit Call class
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
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 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
//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]" | |
} | |
} | |
} |
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
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