简体   繁体   中英

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

 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()
    .toMaybe()
    .ofType(Result.Success.F1::class.java)
    .map {
        ...
    }

If getSomeDataFromService() returns an Observable , you can use Observable.ofType() directly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM