[英]Android - Kotlin Sealed class with Rxkotlin filter
Since sealed is like enum object so i decided to use sealed class for network response, were it contains success or failure if it is success it contains data else error message 由于密封就像枚举对象一样,所以我决定使用密封类进行网络响应,如果成功则包含成功还是失败,如果包含成功则包含数据,否则返回错误消息
Example 例
sealed class Result {
sealed class Success : Result() {
data class F1(val data: Any) : Success()
data class F2(val data: Any) : Success()
}
sealed class Error : Result() {
data class F1(val error: Any) : Error()
data class F2(val error: Any) : Error()
}
}
the above Result class has either Success or Failure 上面的Result类具有成功或失败
getSomeDataFromService()
.filter {
it is Result.Success.F1
}
.map { it: Result
/*
i face problem here,my need is F1 data class but what i
got is Result ,i know that i can cast here,
but i am eager to know for any other solution other than casting
*/
}
}
is there is any other solution ? 还有其他解决方案吗?
Any help 任何帮助
Assuming getSomeDataFromService()
returns a Single
, you should be able to utilize Maybe.ofType() : 假设
getSomeDataFromService()
返回Single
,则您应该能够使用Maybe.ofType() :
getSomeDataFromService()
.toMaybe()
.ofType(Result.Success.F1::class.java)
.map {
...
}
If getSomeDataFromService()
returns an Observable
, you can use Observable.ofType()
directly. 如果
getSomeDataFromService()
返回一个Observable
,则可以直接使用Observable.ofType()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.