How can I store the sharable data in sealed class?...
# android
c
r
It seems like what you’re trying to do is have a sealed set of state-types where one has a result and the others do not(?). Your misstep is that the data class does not implement the sealed parent. If I were to implement this using your code as a starting point, I would have written the following:
Copy code
sealed interface ResultUiState {
    object Prepping : ResultUiState
    object Loading : ResultUiState
    object Idle : ResultUiState
    data class ResultData(
        val a: String,
        val b: Int,
    ) : ResultUiState
}
at the call-site, you’d do something like this
Copy code
fun processResult(result: ResultUiState) {
    when(result) {
        is Prepping -> // do prepping
        is Loading -> // do loading
        is Idle -> // do idling
        is ResultData -> updateUi(result)
    }
}

fun updateUi(result: ResultData) {
    // update your ui
}
c
@rook thanks your answer. Yes, I had incorrect syntax, so I fixed them. And updated the question. The thing is, when non-ResultData state, the UI must keep the data. Think about Kiosk, it has menus, and show the prices. It happens when it's only Success(Here, ResultData). I'd like to show them in non-ResultData state. I use compose and if I use that condition logic, then, the data will be disappear in non-ResultData state.
r
In that case, I recommend leaving the data-containing portions of your UI alone while interpreting the other states. That way, you don't need to worry about preserving the data in every state update.
c
@rook I don't get it. How can I leave them?
r
Are you using Compose or XML framework?
c
I am using compose.
r
I think with Compose, you should definitely wrap the
ResultData
in a
Result
state model and cache the
ResultData
in your view model. That way, you can put the field on all the states as an optional and build them with the cached value if it’s present.
c
You mean taking out the ResultData from the sealed class and keep it in the ViewModel, right? I don't get it. Could you give me more concrete example?