https://kotlinlang.org logo
#compose
Title
# compose
d

ds3fdfd3

12/03/2020, 11:52 AM
Now that navigation-compose library is out, I am trying an app without any fragments and only with compose screens. However, I am getting doubts on where do we create our ViewModels now. Some can be created in Activity scope but there are many optional screen where user may or may not go and it doesn't make sense to create their ViewModel beforehand.
a

allan.conda

12/03/2020, 11:53 AM
Copy code
fun Screen(viewModel: SomeViewModel = viewModel())
or
Copy code
composable("someScreen") {
  val viewModel = viewModel()
  val state = viewModel.state.collectAsState()
  // stateless
  Screen(state, onSomeEvent = viewModel::onSomeEvent)
}
d

ds3fdfd3

12/03/2020, 12:00 PM
I am using the 1st method where I pass the ViewModel to the composable but ViewModel's lifecycle is still associated with the parent activity. If we create it inside composable block not sure what would the scope be (haven't tried that yet)
Copy code
NavHost(navController = navController, startDestination = "login") {
    composable("login") {
        LoginScreen(navController, loginViewModel)
    }
    composable("sms_entry") {
        SmsScreen(navController, loginViewModel)
    }

    composable("map_screen") {
        Text(text = "Logged In")
    }

}
I have something like this. Where loginViewModel is injected in Activity using Hilt
a

allan.conda

12/03/2020, 12:03 PM
not really.
Copy code
// ViewModelStoreOwner and LifecycleOwner
            Providers(
                ViewModelStoreOwnerAmbient provides currentNavBackStackEntry,
                LifecycleOwnerAmbient provides currentNavBackStackEntry
            ) {
                restorableStateHolder.withRestorableState {
                    destination.content(currentNavBackStackEntry)
                }
            }
        }
it’s tied to back stack lifecycle
ohh… Hilt
Yeah, Hilt is tied to Activity and Fragment right now
I’m using a workaround though
you should’ve started by mentioning Hilt 😄
d

ds3fdfd3

12/03/2020, 12:05 PM
Sorry, I thought it was a generic problem. Thanks for the dagger issue link. I will follow it up over there.