With my navigation graph I have three composable views that all share the same view model SellViewModel as shown and all the three views are interacting with the car object inside the sell view model
class SellViewModel : ViewModel() {
var car = mutableStateOf(UsedCar())
fun getMoldBrands() {...}
fun getMoldSpecs() {...}
And my navigation graph :
@Composable()
fun NavGraph() {
val navController = rememberNavController()
val vm = SellViewModel()
NavHost(navController = navController, startDestination = "splash") {
composable("splash") { Splash(navController) }
composable("home") { Home(navController) }
sellGraph(navController, vm)
}
}
fun NavGraphBuilder.sellGraph(navController: NavController , vm : SellViewModel) {
navigation(startDestination = "mold_brands", route = "sell") {
composable("mold_brands") { Brands(nav = navController, vm = vm) }
composable("Mold_specs") { Specs(nav = navController, vm = vm) }
composable("mold_images") { Images(nav = navController, vm = vm) }
}
}
I noticed that when I navigate back to the home screen my sell view model is never destroyed or disposed. and when I navigate for example again to the Brands view the car object still have its previous properties, how can i dispose this view model when i back to the home screen
Update : I updated my sell graph like below
fun NavGraphBuilder.sellGraph(navController: NavController) {
val vm = SellViewModel()
navigation(startDestination = "mold_brands", route = "sell") {
composable("mold_brands") { Brands(nav = navController, vm = vm) }
composable("mold_specs") { Specs(nav = navController, vm = vm) }
composable("mold_images") { Images(nav = navController, vm = vm) }
}
And I use in navigation to the sell views with popUpTo
nav.navigate("sell"){
popUpTo("home")
}
But the view model still in memory and never disposed !
Any ideas, help will be much appreciated