https://kotlinlang.org logo
#compose
Title
# compose
w

wintersoldier

03/02/2022, 8:21 AM
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

ildar.i [Android]

03/02/2022, 8:39 AM
Can't you just expose a StateFlow with your state and call collectAsState on it in your composable?
w

wintersoldier

03/02/2022, 9:01 AM
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

ildar.i [Android]

03/02/2022, 10:21 AM
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

wintersoldier

03/03/2022, 4:16 AM
@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

ildar.i [Android]

03/03/2022, 4:25 AM
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

wintersoldier

03/03/2022, 6:40 AM
I will try this out.