android - 使用 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)
}
解决方案
推荐阅读
- python - pytest 从 python 代码调用到 TravisCI
- android - 制作像 Udacity 这样的应用程序 - 如何托管视频文件?
- xamarin.forms - Xamarin.Forms:启动活动后应用程序崩溃
- python - 如何根据元组列表合并 2 个数据帧,其中每个元组都包含每个数据帧的相关键?
- function - 剪影函数给我一个错误:返回列表中未定义的元素号 2
- javascript - getUserMedia 在网站上工作,但在移动设备上不工作
- python - Groupby 和展平列表
- python - 实时流式传输来自 Pi 的视频帧
- google-cloud-platform - Google Cloud Memory Store (Redis) 使用情况
- java - 在 Java 中将数组声明为全局变量