首页 > 解决方案 > 使用 Either 进行改造 2 响应

问题描述

我创建了一个这样的类:

sealed class Either<out L, out R> {
    //Failure
    data class Left<out L>(val value: L) : Either<L, Nothing>()

    //Success
    data class Right<out R>(val value: R) : Either<Nothing, R>()

    val isRight get() = this is Right<R>
    val isLeft get() = this is Left<L>
}

我正在使用改造,我打算返回这个:

@GET(__SOMEPATH__)
suspend fun pews(__Whatever__) : Either<Throwable, POJO>

但是当Gson尝试创建对象时,会抛出异常:

java.lang.RuntimeException:无法调用没有参数的私有 com.pew.pew.base.networking.Either()

并且

Caused by: java.lang.InstantiationException: Can't instantiate abstract class com.pew.pew.base.networking.Either

有没有办法在改造响应中封装错误和结果?

编辑

现在我有另一个密封类

sealed class Result<T> {
  data class Success<T>(val data: T) : Result<T>()
  data class Unauthorized(val exception: Exception) : Result<Nothing>()
  data class Timeout(val exception: Exception) : Result<Nothing>()
  data class Error(val exception: Exception) : Result<Nothing>()
}
​
fun <A, B> Result<A>.map(mapper: (A) -> B): Result<out B> {
  return when (this) {
    is Success -> Success(mapper(data))
    is Unauthorized -> Unauthorized(exception)
    is Timeout -> Timeout(exception)
    is Error -> Error(exception)
  }
}

然后在我的 RepositoryImpl 中,我需要定义它是成功还是错误。我怎么做?在我使用折叠之前,它允许我获得成功或错误。

我可以做一些类似于从Call<T>to改变的事情Result<T>吗?

inline fun <reified T> execute(f: () -> Call<T>): ResultWrapper<T> =
        try {
            when (T::class) {
                Unit::class -> f().execute().let {
                    ResultWrapper.Success(Unit as T)
                }
                else -> f().execute().body()?.let {
                    ResultWrapper.Success(it)
                } ?: ResultWrapper.Error(Throwable())
            }
        } catch (exception: Exception) {
            ResultWrapper.Network(serverError)
        } 

但它说 在此处输入图像描述

标签: androidkotlingsonretrofit2

解决方案


推荐阅读