0

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?

TomR
  • 2,696
  • 6
  • 34
  • 87

1 Answers1

0

My experiments and tests show that the following works as expected:

composable(JetnewsDestinations.INTERESTS_ROUTE) {
        val interestsViewModel: InterestsViewModel = viewModel(
            viewModelStoreOwner = (LocalContext.current as AppCompatActivity),
            factory = InterestsViewModel.provideFactory(appContainer.interestsRepository)
        )
        InterestsRoute(
            interestsViewModel = interestsViewModel,
            isExpandedScreen = isExpandedScreen,
            openDrawer = openDrawer
        )
    }

My understanding is that AppCompatActivity I can use (my MainActivity is of this type, I have single-activity Jetpack Compose app), but I should be very, very cautious about getting the reference to it, as detailed in How to get activity in compose

TomR
  • 2,696
  • 6
  • 34
  • 87