I want to edit a mutableStateOf Boolean in my ViewModel from Screen1 and observe it in Screen2.
Screen1 Composable, here I observe the state:
@Composable
fun Screen1(vm: MyViewModel = hiltViewModel(), navigate: () -> Unit) {
val myTestBoolean = vm.testBoolean.value
Column() {
if (myTestBoolean) {
Text(text = "myTestBoolean is $myTestBoolean")
}
Button(onClick = { navigate() }) {
Text(text = "Navigate to Screen2")
}
}
}
Screen2 Composable, here I change the mutableStateOf Boolean in my VM to true.
@Composable
fun Screen2(vm: MyViewModel = hiltViewModel(), navigate: () -> Unit) {
Button(onClick = {
vm.setTestBoolean(true)
navigate()
}) {
Text(text = "Back")
}
}
When I click the button here it pops the backstack.
And here is my ViewModel:
@HiltViewModel
class MyViewModel @Inject constructor() : ViewModel() {
private val _testBoolean = mutableStateOf(false)
val testBoolean: MutableState<Boolean> = _testBoolean
fun setTestBoolean(boolean: Boolean){
_testBoolean.value = boolean
}
}
What I want is:
- Navigate from Screen1 to Screen2
- Make some changes and store them in the ViewModel
- Navigate back to Screen1
- See the changes
But its not working as expected, the Boolean is set to true but Screen1 stills says its false even though it recomposes.