【问题标题】:Android - Kotlin Sealed class with Rxkotlin filterAndroid - 带有 Rxkotlin 过滤器的 Kotlin 密封类
【发布时间】:2019-05-09 06:38:55
【问题描述】:

由于密封类似于枚举对象,所以我决定使用密封类进行网络响应,如果成功则包含成功或失败,它包含数据否则错误消息
示例

  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()
            }
        }

上面的Result类有Success或者Failure

 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  
                     */


                }

}

还有其他解决办法吗?
任何帮助

【问题讨论】:

    标签: android kotlin rx-java rx-kotlin2


    【解决方案1】:

    假设getSomeDataFromService() 返回Single,您应该可以使用Maybe.ofType()

    getSomeDataFromService()
        .toMaybe()
        .ofType(Result.Success.F1::class.java)
        .map {
            ...
        }
    

    如果getSomeDataFromService() 返回Observable,则可以直接使用Observable.ofType()

    【讨论】:

    • 是的,这很好,但是如果我想检查多个条件怎么办?
    • 您可以尝试利用许多flatMap*() 操作中的一些。但是您必须考虑到流本身只能包含一种类型。如果您只映射到单一类型,则可能值得在 map() 操作中进行类型检查。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多