What is the correct way of passing constructor arg...
# compose
s
What is the correct way of passing constructor arguments to compose view model using viewModel() in a composable?
👀 1
i
We had talked about retrieving navigation arguments in a ViewModel just the other day: https://kotlinlang.slack.com/archives/CJLTWPH7S/p1614973600447400
What exactly are you trying to do?
s
I want to to pass String argument to viewmodel using viewmodel factory but the problem is in viewmodel factory when I try to return instantiated viewmodel with the String argument I have to grab the other arguments which I am directly injecting through hilt viewmodel ?
i
The whole point of Dagger (and by extension, Hilt), is that all dependencies are found at compile time. The ability to add dependencies (such as your string) at runtime is called assisted injection and the only kind of
@AssistedInject
for ViewModels is arguments, specifically via the
SavedStateHandle
object, which is what that thread I linked to talks about. Here's the Hilt issue for more details: https://github.com/google/dagger/issues/2287
So if you're using Navigation Compose and arguments there, they'll be passed to the
SavedStateHandle
of your
ViewModel
automatically, right alongside your other Hilt provided dependencies
💯 1
s
Oh, I see. thanks a lot, my mistake. I should have passed that
String
as navigation argument so that I can retrieve that via
SaveStateHandle
in
viewModel
.
i
That would be the way to do it if you're using Hilt, yup!
Using Hilt with Navigation Compose should be even easier later this week (if all goes according to plan): https://kotlinlang.slack.com/archives/CJLTWPH7S/p1614619457323100?thread_ts=1614601227.289300&cid=CJLTWPH7S
🎉 3
🤞 1
s
Yes I am using hilt latest artifacts, thanks again.