# android

Isaac Udy

07/16/2020, 10:53 AM
Hello! I'm a library author, and I'm looking to integrate with the new Dagger Hilt setup. One of the features of my library requires injection into an AndroidX ViewModel. Previously, I have provided this functionality through a custom ViewModelFactory, basically in the same way that AbstractSavedStateViewModelFactory works. I am having trouble figuring out how to do something similar for apps that are using Hilt. Is there a way to provide additional
injected parameters to a class that is using


07/16/2020, 10:58 AM
what kind of library are you writing? imo injection/providing/contributing should not really happen inside a library, but in the product implementing the library

Isaac Udy

07/16/2020, 11:10 AM
The library does not control the injecting itself, but rather provides an integration with ViewModels in the same way that SavedStateHandle works. The library is a navigation library that allows you to (optionally) use a "NavigationHandle" to execute navigation actions directly from the ViewModel, without using a LiveData<Event<?>> or similar. SavedStateHandle provides an AbstractSavedStateHandleFactory class, which allows a vanilla Dagger user to create a custom component that provides the SavedStateHandle into a Dagger component to allow this to be injected. My library basically builds on top of that and provides an AbstactNavigationViewModelFactory that extends AbstactSavedStateViewModelFactory. In vanilla dagger, you could define a ViewModelComponent that provides bindings for SavedStateHandle and NavigationHandle, annotate your ViewModels with an
constructor, and write a custom ViewModelFactory that builds the ViewModelComponent and provides the SavedState/Navigation Handle classes into that component to be injected into the ViewModel's
constructor via the Dagger component defined in the library user's application. Does that make sense? A lot of information to dump, sorry. I can't figure out how to do something similar using Hilt.
In short, SavedStateHandle requires a soft reference to the activity to function. SavedStateHandle can be injected in Hilt using the
annotation. I have an object that also needs to be available in the ViewModel, and also requires a soft reference to the activity, but I can't figure out how to mimic the SavedStateHandle's method of injection (because this appears to be tied up in final library classes in Hilt)