Currently i am trying to lern Jetpack Compose. For one part of the App I want to use oen ViewModel for multiple Screens. But the problem described below occures.
I have the following ViewModel:
class NewRoomViewModel : ViewModel() {
private val _floorPlan = mutableStateListOf<FloorPlanWall>()
var floorPlan: SnapshotStateList<FloorPlanWall> = _floorPlan
/* ... */
In the first screen new elements are added to the list.
In the next screen I want to call newRoomViewModel.floorplan.clear()
, but I get the following error: java.util.NoSuchElementException
Both screen fragments access the same instance of the obeject. It is decleared as
private val newRoomViewModel : NewRoomViewModel by viewModels()
in the MainActivity
and passed via the NavGraph to the fragments.
It is also possible to delet single Elements of the list.
PS: Sorry for my bad englisch and if my problem is unclear. I can provide more code.
I tried ti find the source of the problem and the only thing I can say certain is that the list cant be cleared after navigating to the next Screen.
For more context my NavGraph look like this:
@Composable
fun SetupNavGraph(navController: NavHostController, newRoomViewModel : NewRoomViewModel){
NavHost(
navController = navController,
startDestination = Screen.Start.route
){
/* ... */
composable(
route = Screen.NewRoom2.route
){
NewRoom2Fragment(navController = navController, newRoomViewModel = newRoomViewModel)
}
composable(
route = Screen.NewRoom3.route
){
NewRoom3Fragment(navController = navController, newRoomViewModel = newRoomViewModel)
}
}
}
And the screen switch looks like this:
navController.navigate(route = Screen.NewRoom3.route)