Last active
September 12, 2019 12:05
-
-
Save alexfacciorusso/43010274970aa882c1e7 to your computer and use it in GitHub Desktop.
Retrofit Kotlin extensions
This file contains hidden or 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
import retrofit.Call | |
import retrofit.Callback | |
import retrofit.Response | |
import retrofit.Retrofit | |
/** | |
* @author Alex Facciorusso | |
* @since 06/11/15 | |
*/ | |
fun <T> Call<T>.enqueue(success: (response: Response<T>) -> Unit, | |
failure: (t: Throwable) -> Unit) { | |
enqueue(object : Callback<T> { | |
override fun onResponse(response: Response<T>, retrofit: Retrofit) { | |
success(response) | |
} | |
override fun onFailure(t: Throwable) { | |
failure(t) | |
} | |
}) | |
} |
An updated version of @krokofant :
All listeners have their default implementations so no need to call any listener if you don't want to use it.
fun <T : Any> Call<T>.awaitResponse(
onSuccess: (T?) -> Unit = {},
onError: (Message?, Int) -> Unit = { _, _ -> },
onFailure: (Call<T>, String?) -> Unit = { _, _ -> }
) {
this.enqueue(object : Callback<T> {
override fun onResponse(call: Call<T>, response: Response<T>) {
if (response.isSuccessful) {
onSuccess.invoke(response.body())
} else {
val error = ErrorUtils.parseGenericError(response) //Parsing the error in case you need the error message
log("Error: ${error.message} With response code ${response.code()}")
onError.invoke(error, response.code()) // In case you want to handle 403,404 errors.
}
}
override fun onFailure(call: Call<T>, t: Throwable) {
onFailure.invoke(call, t.message)
}
})
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For retrofit2