Skip to content

Instantly share code, notes, and snippets.

@yongjhih
Created October 11, 2022 09:09
Embed
What would you like to do?
For exception handling
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
import retrofit2.Call
import retrofit2.CallAdapter
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
open class CallCallAdapterFactory(private val onResponse: (Call<*>, Response<*>) -> Unit) : CallAdapter.Factory() {
override fun get(returnType: Type, annotations: Array<out Annotation>, retrofit: Retrofit): CallAdapter<*, *>? {
if (getRawType(returnType) != Call::class.java) {
return null
}
val callType = getParameterUpperBound(0, returnType as ParameterizedType)
return CallCallAdapter<Any>(
returnType = callType,
annotations = annotations,
retrofit = retrofit,
onResponse = onResponse,
)
}
}
class CallCallAdapter<T>(
private val returnType: Type,
private val annotations: Array<out Annotation>,
private val retrofit: Retrofit,
private val onResponse: (Call<Any>, Response<Any>) -> Unit,
) : CallAdapter<T, Call<T>> {
override fun adapt(call: Call<T>?): Call<T>? = call?.let { call ->
object : Call<T> by call {
override fun enqueue(callback: Callback<T>) {
call.enqueue(object : Callback<T> by callback {
override fun onResponse(thatCall: Call<T>, response: Response<T>) {
try {
this@CallCallAdapter.onResponse(thatCall as Call<Any>, response as Response<Any>)
callback.onResponse(thatCall, response)
} catch (e: Throwable) {
callback.onFailure(thatCall, e)
}
}
})
}
}
}
override fun responseType(): Type = returnType
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment