为什么我不能在这个Rx变压器中使用接口作为通用types?
我在Kotlin中有以下数据类作为参考:
interface GenericResponse { val error: Error? fun hasErrorObject(): Boolean = error != null } data class LoginResponse( val name: String, val auth: String, @SerializedName("error") override val error: Error? = null ) : GenericResponse
LoginResponse
实现GenericResponse
。 我正在使用以下方式的Retrofit API:
@POST("******") fun createSession(@Body body: LoginBody): Single<Response>
此外,如果存在如下所示,我使用一个变换器从LoginResponse
提取错误:
class ExceptionTransformers { fun wrapRetrofitExceptionSingle(): (Single<Response>) -> Single { return { it: Single<Response> -> it.flatMap { response: Response -> if (response.code() == 200 && response.body() != null) { val genericResponse = response.body() as GenericResponse if (genericResponse.hasErrorObject()) { Single.error { MyException(genericResponse.error!!) } } else { Single.just(response.body()!!) } } else { Single.error { UnknownError() } } } } } }
正如你所看到的,我必须将响应主体转换为GenericResponse
实例,然后在ExceptionTransformer
继续登录。 我的问题是这样的:有没有一种方法使用返回types作为GenericResponse
而不是typesT
(generics)? 我试图做到这一点 – 但遇到了一些错误时,像这样使用它:
fun createSession(loginBody: LoginBody): Single { return apiService.createSession(loginBody) .compose(exceptionTransformers.wrapRetrofitExceptionSingle()) }
从你指定的,似乎T
将永远是GenericResponse
的子types – 添加一个types参数约束可能是你想要的。
fun wrapRetrofitExceptionSingle() { ... }