2

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

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


                }

}

还有其他解决方案吗?
任何帮助

4

1 回答 1

2

假设getSomeDataFromService()返回 a Single,您应该能够使用Maybe.ofType()

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

如果getSomeDataFromService()返回一个Observable,你可以Observable.ofType()直接使用。

于 2019-05-09T07:36:03.847 回答