禁止注入 @HiltViewModel 类,因为它无法正确创建 ViewModel 实例

Pab*_*des 7 android-viewmodel dagger-hilt

我试图将用 @HiltViewModel 注释的 ViewModel 注入到 Fragment 中并收到以下错误:

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
Run Code Online (Sandbox Code Playgroud)

这是否意味着我不应该使用 Hilt 将 ViewModel 注入到 Fragment 中?- 或者是旧的警告已经在最新版本的库中修复。

Pab*_*des 6

我必须直接使用 ViewModelProvider api 而不是 @Inject。

// This does not work
@Inject
lateinit var composeStudyViewModel: ComposeStudyViewModel

// Only traditional method work
val composeStudyViewModel = ViewModelProvider(this)[ComposeStudyViewModel::class.java]

Run Code Online (Sandbox Code Playgroud)

我实际上在官方文档中发现了这一点:

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.
Run Code Online (Sandbox Code Playgroud)

这意味着异常是完全有效的,并指导用户如何将 ViewModel 正确安装到特定的 LifecycleOwner 中。我只是希望 Google 在 Android 官方文档中包含这一点。