1

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

z.g.y
  • 5,512
  • 4
  • 10
  • 36
Rippyae
  • 176
  • 2
  • 14
  • Hoist the `viewModel` creation to `Navhost` seems to prevent the re`init`. – Rippyae Dec 17 '22 at 21:11
  • Do you want to share the same of instance of your ViewModel across all composable and as well as the parent activity? – z.g.y Dec 18 '22 at 01:22

1 Answers1

2

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

z.g.y
  • 5,512
  • 4
  • 10
  • 36