Skip to content

Instantly share code, notes, and snippets.

@alexfacciorusso
Last active September 12, 2019 12:05
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexfacciorusso/43010274970aa882c1e7 to your computer and use it in GitHub Desktop.
Save alexfacciorusso/43010274970aa882c1e7 to your computer and use it in GitHub Desktop.
Retrofit Kotlin extensions
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)
}
})
}
@krokofant
Copy link

For retrofit2

fun <T> Call<T>.enqueue(success: (response: Response<T>) -> Unit,
                        failure: (t: Throwable) -> Unit) {
    enqueue(object : Callback<T> {
        override fun onResponse(call: Call<T>?, response: Response<T>) = success(response)

        override fun onFailure(call: Call<T>?, t: Throwable) = failure(t)
    })
}

@deepakkumardk
Copy link

deepakkumardk commented Sep 12, 2019

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