Florian
08/12/2021, 12:05 PMhilt
)`viewModel()` in the activity and pass it to my Composable screen?Tgo1014
08/12/2021, 12:08 PMhiltViewModel()
directly in the composable parameter for ViewModel
Florian
08/12/2021, 12:27 PMTgo1014
08/12/2021, 1:02 PMColton Idle
08/12/2021, 4:19 PMFlorian
08/12/2021, 10:04 PMIan Lake
08/16/2021, 5:39 PMhiltViewModel()
/ viewModel()
use LocalViewModelStoreOwner.current
- when you're in an Activity/Fragment, that'll be the default. When you're within a NavHost
, it'll be that current destination. You'll just need to be explicit if you want something other than the default
val outerOwner = LocalViewModelStoreOwner.current
NavHost(...) {
composable(...) {
val outerScopedViewModel: MyViewModel = viewModel(outerOwner)
}
}
Ian Lake
08/16/2021, 5:42 PMNavHost
, that's exactly why you can define a route for your root navigation graph (the one that is always present):
NavHost(navController, startDestination = "home", route="root") {
composable(...) {
val rootScopedViewModel: MyViewModel = viewModel(navController.getBackStackEntry("root"))
}
}
Florian
08/16/2021, 7:02 PMhiltViewModel()
) and then pass it down through to that Composable?Florian
08/16/2021, 7:03 PMonCreate
Ian Lake
08/16/2021, 7:13 PMColton Idle
08/16/2021, 7:15 PMIan Lake
08/16/2021, 7:27 PMColton Idle
08/16/2021, 8:16 PMprivate val sharedViewModel: ActivityViewModel by activityViewModels()
How would I do this in the compose world since all of my destinations/screens are in my NavHost?Ian Lake
08/16/2021, 9:21 PMactivityViewModels()
is doing? https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:fragment[…]main/java/androidx/fragment/app/FragmentViewModelLazy.kt;l=80
It is just getting the activity and using its ViewModelStore
, just like any other ViewModelStoreOwner
Ian Lake
08/16/2021, 9:22 PMouterOwner
approach I mentioned aboveColton Idle
08/16/2021, 10:31 PMFlorian
08/17/2021, 12:24 AMFlorian
08/17/2021, 12:24 AMFlorian
08/17/2021, 12:26 AMIan Lake
08/17/2021, 12:31 AMFlorian
08/17/2021, 8:56 AMFlorian
08/17/2021, 11:10 AMFlorian
08/17/2021, 11:12 AMFlorian
08/17/2021, 11:12 AMIan Lake
08/17/2021, 1:30 PMviewModel()
- what matters is using the right owner.Florian
08/17/2021, 2:30 PMFlorian
08/17/2021, 2:30 PM!!
Florian
08/17/2021, 2:31 PMhiltViewModel()
Florian
08/17/2021, 2:31 PMhiltViewModel()
does that automatic scopingIan Lake
08/17/2021, 4:48 PMhiltViewModel()
just calls viewModel()
with a Hilt provided factory. They both internally do the !!
for you and throw if it isn't there (which, like I said, it will always be there in an activity/fragment)Florian
08/17/2021, 4:58 PM