Jetnews demo application uses this code for retrieving ViewModel https://github.com/android/compose-samples/blob/main/JetNews/app/src/main/java/com/example/jetnews/ui/JetnewsNavGraph.kt :
composable(JetnewsDestinations.INTERESTS_ROUTE) {
val interestsViewModel: InterestsViewModel = viewModel(
factory = InterestsViewModel.provideFactory(appContainer.interestsRepository)
)
InterestsRoute(
interestsViewModel = interestsViewModel,
isExpandedScreen = isExpandedScreen,
openDrawer = openDrawer
)
}
viewModel
has documentation for the viewModelStoreOwner
:
viewModelStoreOwner: ViewModelStoreOwner = checkNotNull(LocalViewModelStoreOwner.current)
viewModelStoreOwner - The owner of the ViewModel that controls the scope and lifetime of the returned ViewModel. Defaults to using LocalViewModelStoreOwner.
https://stackoverflow.com/a/58893398/1375882 assures that both Fragment
and Activity
is ViewModelStore
- implements relevenat capability.
My question is - how can I get access to the Activity
as the ViewModelStore
in the NavGraph
composable(ROUTE)
code block (which is @Composable
apparently) and use is as viewModelStoreOwner
argument for creating/retrieving activity-wide ViewModel
instance? Is this possible at all? This block is part of @Composable
and the reference to Activity
my induce some leaks, isn't it?