Search code examples
androidkotlinandroid-jetpack-composeandroid-viewmodeljetpack-compose-navigation

How to persist ViewModel when navigating in Android?


new to android, and doing it the Compose way.

I have a BottomNavigation and three taps, each draw a different screen.

@Composable
fun SetupNavigation(navHostController: NavHostController) {
    NavHost(navController = navHostController, startDestination = "home") {
        composable(route = "first") {
            FirstScreen()
        }
        composable(route = "second") {
            SecondScreen()
        }
        composable(route = "third") {
            ThirdScreen()
        }
    }
}
@Composable
fun FirstScreen(
    firstScreenViewModel: FirstScreenViewModel = hiltViewModel()
) {
    val uiState by firstScreenViewModel.uiState.collectAsState()
    Log.i("FirstScreen", "uiState: $uiState")
    val coins = uiState.coinsList

    ItemsList(items = items)
}

Using the backbutton or just tapping through each viewModel of the different screens seems to reinit. Is that the expected behavior? I like to persist the viewModel when switching routes.

I don't have fragments, just one activity with composable

TIA


Solution

  • If you want to share viewModel instance across your Nav Graph and your host activity you can do 2 things

    one is assigning the local ViewModelStoreOwner

    @Composable
    fun SetupNavigation(navHostController: NavHostController) {
    
        val viewModelStoreOwner = checkNotNull(LocalViewModelStoreOwner.current) {
            "No ViewModelStoreOwner was provided via LocalViewModelStoreOwner"
        }
    
        NavHost(navController = navHostController, startDestination = "home") {
            composable(route = "first") {
                FirstScreen(firstScreenViewModel = hiltViewModel(viewModelStoreOwner))
            }
            composable(route = "second") {
                SecondScreen() // you can also do it here if you want
            }
            composable(route = "third") {
                ThirdScreen() // you can also do it here if you want
            }
        }
    }
    

    or another approach is creating a Local composition of your Activity instance and set it up like this