【问题标题】:android hilt Inject into ViewModelandroid hilt注入ViewModel
【发布时间】:2021-06-19 07:00:06
【问题描述】:

我正在尝试向 MyViewModel 注入一个模块

这是我的模块

@Module
@InstallIn(ViewModelComponent::class)
object EngineModule {
    @Provides
    fun getEngine(): String = "F35 Engine"
}

这是我的视图模型

@HiltViewModel
class MyViewModel @Inject constructor(): ViewModel() {
    @Inject lateinit var getEngine: String

    fun getEngineNameFromViewModel(): String = getEngineName()
}

它会抛出

kotlin.UninitializedPropertyAccessException: 后期初始化属性 getEngine 尚未初始化

但是,如果我将 ViewModelComponent::class 更改为 ActivityComponent::class 并像这样注入

@AndroidEntryPoint
class MainActivity : ComponentActivity() {

    @Inject
    lateinit var getEngine: String

效果很好

知道如何注入视图模型吗?

【问题讨论】:

    标签: android android-viewmodel dagger-hilt


    【解决方案1】:

    您也可以删除 @Inject constructor,因为您已经使用 dagger 模块提供了依赖项:

    @HiltViewModel 
    class MyViewModel (private val engineName: String): ViewModel() {
    
        fun getEngineNameFromViewModel(): String = engineName
    
    }
    

    所以,基本上你可以使用 dagger 模块或构造函数注入来提供依赖。

    【讨论】:

      【解决方案2】:

      由于将在ViewModel的构造函数中注入所需的依赖项,因此您只需按以下方式修改代码即可使其工作:

      @HiltViewModel 
      class MyViewModel @Inject constructor(private val engineName: String): ViewModel() {
      
          fun getEngineNameFromViewModel(): String = engineName
      
      }
      

      【讨论】:

      • 感谢您的回复,它会抛出 java.lang.RuntimeException: Cannot create an instance of class com.example.hilttest.viewModel.MyViewModel,我猜是因为我在我的可组合屏幕中使用 viewModel,就像这样 @Composable fun ScreenOne(myViewModel: MyViewModel = viewModel()) 没有使用工厂
      • 那是另一个问题,不是你要的...不同的问题,不同的问题,或者只是编辑这些添加问题的全貌。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-18
      • 1970-01-01
      • 1970-01-01
      • 2021-06-24
      • 1970-01-01
      • 1970-01-01
      • 2021-02-12
      相关资源
      最近更新 更多