Reputation: 954
I am trying to inject a ViewModel annotated with @HiltViewModel into a Fragment and get the following error:
Injection of an @HiltViewModel class is prohibited since it does not create a ViewModel instance correctly.
Access the ViewModel via the Android APIs (e.g. ViewModelProvider) instead.
Injected ViewModel: com.example.MyViewModel
Is that meaning I should not use Hilt to inject ViewModels into Fragments? - Or is an old warning already fixed in newest versions of the library.
Upvotes: 16
Views: 5541
Reputation: 954
I had to use the ViewModelProvider api directly instead of @Inject.
// This does not work
@Inject
lateinit var composeStudyViewModel: ComposeStudyViewModel
// Only traditional method work
val composeStudyViewModel = ViewModelProvider(this)[ComposeStudyViewModel::class.java]
I actually found out this in the official documentation:
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 user about how to install the ViewModel properly into the specific LifecycleOwner. I just wish Google had that in the Android official documentation.
Upvotes: 8
Reputation: 66516
You can use
val taskViewModel: ComposeStudyViewModel by viewModels()
instead of using one with ViewModelProvider
https://developer.android.com/training/dependency-injection/hilt-jetpack
Upvotes: 11