【发布时间】: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