https://kotlinlang.org logo
s

Shivam Sethi

03/07/2021, 11:02 PM
What is the correct way of passing constructor arguments to compose view model using viewModel() in a composable?
👀 1
i

Ian Lake

03/07/2021, 11:48 PM
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

Shivam Sethi

03/07/2021, 11:54 PM
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

Ian Lake

03/08/2021, 12:02 AM
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

Shivam Sethi

03/08/2021, 12:07 AM
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

Ian Lake

03/08/2021, 12:51 AM
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

Shivam Sethi

03/08/2021, 8:19 AM
Yes I am using hilt latest artifacts, thanks again.
2 Views