So more specifically, my question is, can I use `a...
# android
c
So more specifically, my question is, can I use
androidx.activity
function
viewModels()
and pass dependencies to e.g.
MyViewModel
?
a
Dependency injection frameworks like Dagger, and Dagger Hilt can help you with that. Otherwise you would be writing your own ViewModelFactory, basically
c
I am using Hilt, but I don’t see how it matters here when using
by viewModels()
lazy instantiation in activity-ktx artifact, see: https://developer.android.com/topic/libraries/architecture/viewmodel-savedstate
a
You can use `@ViewModelInject`to inject dependencies to your constructor. Hilt will generate the ViewModelFactory for you
and you can use
viewModels()
directly. You can also inject
SavedStateHandle
with
@Assisted
Copy code
class MainViewModel 
@ViewModelInject 
constructor(
    private val repository: Repository,
    @Assisted private val savedStateHandle: SavedStateHandle
): ViewModel()
c
thanks @allan.conda yep I’m taking a look now
I’m trying to figure out what dependency I’m missing
@ViewModelInject doesn’t appear to be in the core Hilt deps?
a
yes, it’s androidx.hilt
c
amazing, thank you!
😎 1