https://kotlinlang.org logo
p

Pablichjenkov

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: https://stackoverflow.com/questions/73931588/injection-of-an-hiltviewmodel-class-is-prohibited-since-it-does-not-create-a-vi
I had to use the ViewModelProvider api directly instead of @Inject.
Copy code
@HiltViewModel
class ComposeStudyViewModel @Inject constructor(){}

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

// Had to use the ViewModelProvider directly
val composeStudyViewModel = ViewModelProvider(this)[ComposeStudyViewModel::class.java]
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.
22 Views