Not sure if a question or vent but how do you guys...
# compose
z
Not sure if a question or vent but how do you guys feel about the magic that happens with NavHost and ViewModels SavedStateHandle? This is the first time in Kotlin where I see arguments being magically passed. See screenshot. Is there an alternative method of passing down an argument to VM so I can use them in the
init
?
this just works but doesn't feel alright. One issue I got is if I ever change the endpoint or rename slug I also have to check the variables used in the ViewModel... forcing me to use constants
s
Not super helpful but Koin allows assisted injection so you can have this slug be a constructor dependency
z
Koin seems to be the easier solution but I'd like to stick to Dagger/Hilt for professional work purposes
👍 1
i
The only thing Dagger/Hilt allows for assisted injection at the moment is the
SavedStateHandle
as per this issue: https://github.com/google/dagger/issues/2287
And there really isn't that much 'magic' there -
hiltViewModel
looks at the
LocalViewModelStoreOwner
. Within a
composable
destination, that would be its
NavBackStackEntry
. Each
NavBackStackEntry
has the set of arguments parsed from your route - those are passed through to Hilt's ViewModelFactory which is based on a `SavedStateViewModelFactory`: https://developer.android.com/reference/androidx/lifecycle/SavedStateViewModelFactory
You'll note the constructor there that takes a set of
defaultArgs
- that's what populates the
SavedStateHandle
with the arguments from your
NavBackStackEntry
There's some work being done in ViewModels themselves, namely in https://issuetracker.google.com/issues/188541057, that makes it way easier to inject additional information into the ViewModel Factory (i.e., exactly what assisted injection tries to do). Still early days (nothing released yet), so it'll be awhile until any Dagger/Hilt integration that leverages that new capability becomes available
z
Thank you Ian!