我在 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>>
此外,我使用转换器从
LoginResponse
中提取错误。如果存在如下图:class ExceptionTransformers {
fun <T> wrapRetrofitExceptionSingle(): (Single<Response<T>>) -> Single<T> {
return { it: Single<Response<T>> ->
it.flatMap { response: Response<T> ->
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
中继续登录.我的问题是:有没有办法将返回类型用作 GenericResponse
而不是输入 T
(通用)?我曾尝试这样做 - 但在像这样使用它时遇到了许多错误:fun createSession(loginBody: LoginBody): Single<LoginResponse> {
return apiService.createSession(loginBody)
.compose(exceptionTransformers.wrapRetrofitExceptionSingle())
}
最佳答案
从您指定的内容来看,似乎是 T
将始终是 GenericResponse
的子类型- 添加类型参数约束可能是您想要的。
fun <T : GenericResponse> wrapRetrofitExceptionSingle() {
...
}
关于generics - 为什么我不能在这个 Rx 转换器中使用接口(interface)作为泛型类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47515612/