Skip to content

Instantly share code, notes, and snippets.

@llleodeleon
Created August 23, 2019 20:13
Show Gist options
  • Save llleodeleon/05d313c5e33d120efbc7bfbc79823ccf to your computer and use it in GitHub Desktop.
Save llleodeleon/05d313c5e33d120efbc7bfbc79823ccf to your computer and use it in GitHub Desktop.
class ResultsCallAdapterFactory private constructor() : CallAdapter.Factory() {
companion object {
@JvmStatic
fun create() = ResultsCallAdapterFactory()
}
override fun get(returnType: Type, annotations: Array<Annotation>, retrofit: Retrofit): CallAdapter<*, *>? {
return try {
val enclosedType = returnType as ParameterizedType
val responseType = getParameterUpperBound(0, enclosedType)
val rawResultType = getRawType(responseType)
val delegate: CallAdapter<Any, Any> = retrofit.nextCallAdapter(this, enclosedType, annotations) as CallAdapter<Any, Any>
if (rawResultType != Results::class.java)
null
else {
object : CallAdapter<Any, Results<Any>> {
override fun adapt(call: Call<Any>): Results<Any> {
return delegate.adapt(ResultsCall(call)) as Results<Any>
}
override fun responseType(): Type {
return delegate.responseType()
}
}
}
} catch (e: ClassCastException) {
null
}
}
}
class ResultsCall<T>(private val call: Call<T>): Call<T> {
override fun enqueue(callback: Callback<T>) {
call.enqueue(object : Callback<T>{
override fun onFailure(call: Call<T>, t: Throwable) {
}
override fun onResponse(call: Call<T>, response: Response<T>) {
}
})
}
override fun isExecuted()= call.isExecuted
override fun clone(): Call<T> = call.clone()
override fun isCanceled() = call.isCanceled
override fun cancel() = call.cancel()
override fun execute(): Response<T> = call.execute()
override fun request(): Request = call.request()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment