Map Retrofit RxJava Result到密封类Success和failure



我正在使用RXJava来调用我的api,我试图将我的调用结果映射到密封类的成功和失败部分,

我做映射部分,但我总是得到这个错误java.lang。RuntimeException:没有参数调用private Result()失败

下面是我的代码: <<p>改造接口/strong>
@POST("$/Test")
fun UpdateProfile(@Body testBody: TestBody): Single<Result<TestResult>>

结果密封类

sealed class Result<T> {
data class Success<T>(val value: T) : Result<T>()
data class Failure<T>(val throwable: Throwable) : Result<T>()}

调用和映射

webServices.UpdateProfile(testBody)
.onErrorReturn {
Failure(it)
}
.map {
when (it) {
is  Result.Failure ->  Failure(it.throwable)
is  Success -> Success(it.value)
}
}.subscribe()

有人能帮忙吗?为什么我得到这个错误?

问题是您的改装接口返回类型:Single<Result<TestResult>>。Retrofit无法知道您的Result是多态类型,它只会尝试实例化您指定的任何类。在这种情况下,Result不能直接实例化,因为它是密封的。

您需要使用非多态返回类型,或者相应地配置改造。

相关内容