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

Nikola Drljaca

03/05/2021, 7:46 PM
Is there any way to grab arguments inside a
viewModel
when using
navigation-compose
?
i

Ian Lake

03/05/2021, 8:00 PM
The
SavedStateHandle
of a ViewModel will automatically be populated with the arguments of the destination
🙏 2
👌 1
n

Nikola Drljaca

03/05/2021, 8:04 PM
And that is true even though I'm using navigate-compose?
That question is redundant, sorry 😅
g

Gabriel

03/05/2021, 8:36 PM
@Ian Lake are there any examples combining navigation and viewmodel as you've described?
z

zoha131

03/05/2021, 8:47 PM
@Ian Lake is this something new that is being working on? that would be really awesome!
i

Ian Lake

03/05/2021, 8:49 PM
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

zoha131

03/05/2021, 8:56 PM
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

Ian Lake

03/05/2021, 9:00 PM
You are correct. That has indeed always been the case
z

zoha131

03/05/2021, 9:01 PM
wow. thanks for this. I wish I knew it earlier.
g

Gabriel

03/05/2021, 9:14 PM
@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

Ian Lake

03/05/2021, 9:15 PM
it
- the
NavBackStackEntry
is a
SavedStateRegistryOwner
g

Gabriel

03/05/2021, 9:16 PM
🤦
of course it is