【发布时间】:2019-12-28 17:14:55
【问题描述】:
我需要在我的 api 中进行自定义错误处理,并且我想在新版本的 Retrofit 中使用协程。由于我们不再需要使用Deferred,我们自己的 Jake Wharton 一个月前在 reddit 上写了这篇文章
但我在正确创建 CallAdapterFactory 时遇到问题。
具体来说,我不明白:“委托给内置工厂,然后将值包装在密封类中”
是否有人已经在使用此设置可以提供帮助?
这是当前代码
sealed class Results<out T: Any> {
class Success<out T: Any>(val response: T): Results<T>()
class Failure(val message: String, val serverError: ServerError?): Results<Nothing>()
object NetworkError: Results<Nothing>()
}
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,returnType,annotations) as CallAdapter<Any,Any>
if(rawResultType != Results::class.java)
null
else {
object: CallAdapter<Any,Any>{
override fun adapt(call: Call<Any>): Any {
val response = delegate.adapt(call)
//What should happen here?
return response
}
override fun responseType(): Type {
return delegate.responseType()
}
}
}
} catch (e: ClassCastException) {
null
}
}
}
【问题讨论】:
-
我遇到了问题解释
-
But I'm having problems creating the CallAdapterFactory properly解释 -
我不确定您的编辑应该解释什么
-
“委托然后包装在密封类中”,我不明白该怎么做
-
您是否使用
SealedClass,因为从 Jakes 上下文看来,这与密封类有关。
标签: android retrofit retrofit2 kotlin-coroutines retrofit2.6