I develop the app in Compose and MVVM architecture. I have viewModel with state of view per screen. ViewModel:
class ProfileViewModel : ViewModel() {
private val _state = MutableStateFlow(ProfileViewState())
val state: StateFlow<ProfileViewState> get() = _state
val actions = Channel<ProfileAction>()
init {
viewModelScope.launch {
combine(_state) {
ProfileViewState()
}.collect {
_state.value = it
}
}
}
State:
class ProfileViewState {
val nick: MutableStateFlow<String> = MutableStateFlow("default nick")
}
When user press the button I change value of "nick" in state.
_state.value.nick.value = "new nick"
I want to observe the state in my view and update data automatically when they changed
@Composable
fun ProfileScreen() {
val viewModel: ProfileViewModel = viewModel()
val viewState by viewModel.state.collectAsState()
}
TextView where I try to display "nick" value
Text(text = viewState.nick.value, style = MaterialTheme.typography.h4)
The problem is that when I change data in state, screen doesn't react and doesn't update. When I open ProfileScreen I get the same instance of state(?) with default values