【问题标题】:Retrofit 2.6.0: Custom Coroutines CallAdapterFactoryRetrofit 2.6.0:自定义协程 CallAdapterFactory
【发布时间】:2019-12-28 17:14:55
【问题描述】:

我需要在我的 api 中进行自定义错误处理,并且我想在新版本的 Retrofit 中使用协程。由于我们不再需要使用Deferred,我们自己的 Jake Wharton 一个月前在 reddit 上写了这篇文章

https://github.com/square/retrofit/blob/master/samples/src/main/java/com/example/retrofit/RxJavaObserveOnMainThread.java

但我在正确创建 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


【解决方案1】:

我已经创建了一个这样的工厂的例子,你可以找到它here on GitHub。也可以看看类似的问题:How to create a call adapter for suspending functions in Retrofit?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-10
    • 2020-01-04
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-25
    相关资源
    最近更新 更多