0

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

Mohammed Riyadh
  • 883
  • 3
  • 11
  • 34

1 Answers1

1

SellViewModel will never destroyed from your code. Because, you initiated it inside fun NavGraphBuilder.sellGraph and this fun will never become unused state.

If you want your viewModel to be disposed when you navigate to other screen, you have to initiate the viewModel inside that composable like below.

@Composable
fun Brands(nav: NavController, viewModel: SellViewModel = hiltViewModel()) {
  ...
}

or 


@Composable
fun Brands(nav: NavController) {
  val viewModel: SellViewModel = viewModel()
  ...
}