Skip to content

Instantly share code, notes, and snippets.

@ehbc221
Last active September 17, 2021 12:48
Show Gist options
  • Save ehbc221/20777d60aa331c587b2754d1e899716b to your computer and use it in GitHub Desktop.
Save ehbc221/20777d60aa331c587b2754d1e899716b to your computer and use it in GitHub Desktop.
package com.example.network
import android.util.Log
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import com.example.utils.ErrorUtils
/**
* Extension for awaitResponse
*/
fun <T : Any> Call<T>.awaitResponse(
onSuccess: (T?) -> Unit = {},
onError: (String, Int) -> Unit = { _, _ -> },
onFailure: (Call<T>, String?) -> Unit = { _, _ -> }
) {
// Extension for Enqueue
this.enqueue(object : Callback<T> {
val TAG = "BaseRetrofitEnqueue"
/**
* OnResponse Callback
*/
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.d(TAG, "Error: ${error.message()} With response code ${response.code()}")
onError.invoke(error.message(), response.code()) // In case you want to handle 403,404 errors.
}
}
/**
* OnFailure Callback
*/
override fun onFailure(call: Call<T>, t: Throwable) {
onFailure.invoke(call, t.message)
}
})
}
@ehbc221
Copy link
Author

ehbc221 commented Dec 22, 2020

// ErrorUtils class

package com.example.utils

import retrofit2.Response

class ErrorUtils {

companion object {

    /**
     * Parse a generic Error
     */
    fun <T: Any> parseGenericError(response: Response<T>): Response<T> {
        return response
    }
}

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment