Last active
September 17, 2021 12:48
-
-
Save ehbc221/20777d60aa331c587b2754d1e899716b to your computer and use it in GitHub Desktop.
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
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) | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
// ErrorUtils class
package com.example.utils
import retrofit2.Response
class ErrorUtils {
}