Is there any way to grab arguments inside a `viewM...
# compose
n
Is there any way to grab arguments inside a
viewModel
when using
navigation-compose
?
i
The
SavedStateHandle
of a ViewModel will automatically be populated with the arguments of the destination
🙏 2
👌 1
n
And that is true even though I'm using navigate-compose?
That question is redundant, sorry 😅
g
@Ian Lake are there any examples combining navigation and viewmodel as you've described?
z
@Ian Lake is this something new that is being working on? that would be really awesome!
i
This has been the case since Navigation 2.2.0, released over a year ago, which was the release that added support for
SavedStateViewModelFactory
(which is what gives you
SavedStateHandle
): https://developer.android.com/jetpack/androidx/releases/navigation#2.2.0
There's nothing Navigation Compose specific about this, just another thing you get for free
(the same thing happens with activities and fragments getting their extras/arguments when using
SavedStateHandle
there)
z
correct me if I am wrong. If I require a String as the argument for the destination. then I will get the argument automatically inside
SavedStateHandle
even if I use compose.
i
You are correct. That has indeed always been the case
z
wow. thanks for this. I wish I knew it earlier.
g
@Ian Lake if we're scoping the viewmodel to a composable, what's the SavedStateRegistryOwner?
Copy code
composable(Screen.LaunchScreen.route) {
            val playersViewModel = viewModel<PlayersViewModel>(
                factory = PlayersViewModelFactory(
                    this,<--- what should this be?
                    PlayersRepository()
                )
            )
            LaunchScreen(playersViewModel)
        }
Or do we need to it in the activity for this to work?
i
it
- the
NavBackStackEntry
is a
SavedStateRegistryOwner
g
🤦
of course it is