I have an app with two activities. Activity1 changes a State stored in a ViewModel, then starts Activity2. But somehow, the state change is only reflected in Activity1, not in Activity2.
ViewModel
class MyViewModel : ViewModel() {
var hasChanged: Boolean by mutableStateOf(false)
}
Composable of Activity1
@Composable
fun Screen1() {
val context = LocalContext.current
val viewModel: MyViewModel = viewModel()
Column {
Text("State changed: " + viewModel.hasChanged.toString())
Button(
onClick = {
viewModel.hasChanged = true
startActivity(context, Intent(context, Activity2::class.java), null)
}
) {
Text("Change State!")
}
}
}
Composable of Activity2
@Composable
fun Screen2() {
val viewModel: MyViewModel = viewModel()
Text("State changed: " + viewModel.hasChanged.toString()) # stays 'false'
}
Behavior of the app
Activity1correctly shows the state to befalse, initially- After button is pressed,
Activity1correctly displays the state to betrue Activity2opens but still shows the state to befalse

Question
Why is the state change not reflected in Activity2 and can this be fixed?