10/12/2022, 10:26 AM
Hi there, Quick one in regards to dagger-hilt. I am getting a build exception when using @HiltViewModel annotation. This is the link to SO:
I had to use the ViewModelProvider api directly instead of @Inject.
Copy code
class ComposeStudyViewModel @Inject constructor(){}

// This does not build, I get build dagger-hilt exception
lateinit var composeStudyViewModel: ComposeStudyViewModel

// Had to use the ViewModelProvider directly
val composeStudyViewModel = ViewModelProvider(this)[]
Apparently Hilt version 2.44 doesn't allow for @Inject ViewModel directly. Tried 2 different project setups and get the same, unless there is something wrong with my environment, wrong transitive dependency or something else.
I actually found out in the original documentation:
Copy code
Warning: Even though the view model has an @Inject constructor, it is an error to request it from Dagger directly (for example, via field injection) since that would result in multiple instances. View Models must be retrieved through the ViewModelProvider API. This is checked at compile time by Hilt.
Meaning that the Exception is completely valid, and guide the users on about how to properly install the ViewModel instance into the specific LifecycleOwner. I just wish Google had that in the Android official hilt integration guide.