Whats the best way to do State Management for comp...
# compose
w
Whats the best way to do State Management for compose , do anyone have some best approaches reads or sample I can take a look. I have tried state hoisting in viewmodel for `InputField`but it was bit messy since there was lot of state for error , label , placeholder and data . Any suggestions will be helpful
i
Can't you just expose a StateFlow with your state and call collectAsState on it in your composable?
w
Have done that , but the thing is its not best to do it in that way. Lets say an example of inputting name . val name = MutableLiveData(“”) now for collecting it val nameState = viewmodel.name.collectAsState() the problem here is there can be MutableLiveData for error, placeholder , data and label , also there can be many other components on that screen , how to handle that?
i
Copy code
private val _stateStateFlow: MutableStateFlow<MyState> = MutableStateFlow(MyState())
val stateStateFlow: StateFlow<MyState> = _stateStateFlow

class MyState(
    val name: String,
    val error: String,
    val placeholder: String,
    val label: String,
)
you can make an object incapulating your state. and in composable just
Copy code
val stateState = vm.stateStateFlow.collectAsState().value
Text(stateState.label)
👍 2
there is a bit of confusion, since we’re talking about three states: your state, StateFlow and composable state
w
@ildar.i [Android], This one is yeah a good approach , but I was wondering , lets say you 10 textfield , an appbar with a search so basically you need to have atleast 11 State class right?
i
No, there should be just one state, encapsulating all 10 fields. it can control other fields (color, visibility) based on combinations of inputs. Basically, a single source of truth
w
I will try this out.