marios proto
06/10/2021, 12:02 PMStateFlow
of different states. e.g.
sealed class MyState{
object Loading…
class ShowList(val list:List<String> ) …
class Itemselected( val item:String)...
class Error( val message:String )…
}
and then on the content I want to display something like
@Composable
fun MyPage(viewModel: MyViewModel) {
val state: MyState by viewModel.getStateFlow()
.collectAsState(initial = MyState.Loading)
Column {
Header("Home")
PageBody(state)
}
}
@Composable
fun PageBody(state: ServiceHubHomeState) {
when (state) {
MyState.Loading -> Header("Loading")
is MyState.ShowList ->
ListHub(serviceItems = state.list)
is MyState.ItemSelected -> { // do something else
}
}
}
So now, when I use .collectAsState, everything works all-right, BUT,
when I have already published a value of Showlist, and a list is rendered,
if a new state comes, e.g ItemSelected of course the list is cleaned up.
My question is, how do I keep the already rendered list between the next state transitions?
I am sure I have to keep the state somewhere but cannot see it 😞Albert Chang
06/10/2021, 12:44 PMLoading
is a State, but ShowList
and ItemSelected
are not, they are events. You are mixing states and events. Your state flow should contain two states: Loading
and List
, and ItemSelected
should be emitted by another event flow.marios proto
06/10/2021, 12:58 PMAlbert Chang
06/10/2021, 1:24 PMItemSelected
or whatever do not overwrite List
state, it is surely not a state, or at least not a state at the same level with List
.Arkadii Ivanov
06/10/2021, 1:34 PMMyState
sealed class means that only one possible variant can be displayed at a time. If you need to display multiple things, they all should be part of the same state variant:
sealed class MyState {
object Loading
class List
class ListWithItemSelected
class Error
}
or
sealed class MyState {
object Loading
class List(val list: SomeType, val selectedItem: SomeOtherType? = null)
class Error
}
marios proto
06/10/2021, 2:07 PM