Android 用于改装2响应
我创建了这样一个类:Android 用于改装2响应,android,kotlin,gson,retrofit2,Android,Kotlin,Gson,Retrofit2,我创建了这样一个类: 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 isRigh
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>
}
是否有任何方法封装改装响应的错误和结果
编辑
现在我有了另一个密封类
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)
}
}
密封类结果{
数据类成功(val数据:T):结果()
未经授权的数据类(val异常:异常):结果()
数据类超时(val异常:异常):结果()
数据类错误(val异常:异常):结果()
}
有趣这不是改造的工作。这是调用此改造API的存储库的工作,或者是下游的其他工作(例如,将响应转换为ViewState的viewmodel)。改型生成的API(pews()
)将抛出异常;您的一些下游代码将需要一个try
/catch
结构来捕获这些异常。如果你想在你的other
结构中包装它们,欢迎你这么做。但是由于pews()
的原因,我不能使用other
,对吗?我应该使用类似于包含结果和错误的密封类的东西吗?像Result和repositoryImpl一样,执行平面映射或任何操作来重新调用Result.Success(it)或Result.Failure(Throwable())?“但是我不能将两者都用作pews()的结果,对吗?”--正确,因为没有任何东西可以创建该实例。“我应该使用类似于包含结果和错误的密封类的东西吗?”——改型API将返回POJO
。存储库可以选择将POJO
或任何Throwable
包装到或其他密封类中。或者,在viewmodel或使用存储库的其他代码中处理该问题。我倾向于使用自然异常传播,直到我接近UI层(例如viewmodel),然后再将异常包装到某个东西(例如viewstate)。@Commonware请检查我的编辑。如果您有suspend-fun-pews():POJO
,则使用Result.Success(api.pews())
,其中,api
是改装生成的api的一个实例。假设其他三种结果
状态基于异常类型,将结果.Success(api.pews())
包装在中,尝试使用返回其他结果
类型的catch
子句构造catch
。
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)
}
}
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)
}