0

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:

  1. Navigate from Screen1 to Screen2
  2. Make some changes and store them in the ViewModel
  3. Navigate back to Screen1
  4. 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.

HavanaSun
  • 446
  • 3
  • 12
  • 39
  • @nglauber That solved it, thank you! – HavanaSun Apr 19 '22 at 14:27
  • Why is this closed??? Just because these is one answer doesn't mean there might not be a better one.... – eimmer Apr 19 '22 at 15:08
  • @eimmer you can vote for reopen the question, I just felt stupid so I closed it, I didn't even consider googling for "how to share viewModel between composables" – HavanaSun Apr 19 '22 at 17:25

1 Answers1

0

You can observe the state of testBoolean using observeAsState().

val myTestBoolean = vm.testBoolean.observeAsState().value

Use this inside composable from where you want to observe i.e. in your case Screen2