【问题标题】:Cannot create an instance of class ViewModel using dagger hilt无法使用匕首刀柄创建 ViewModel 类的实例
【发布时间】:2021-04-25 12:02:47
【问题描述】:

我的视图模型:

class LoginViewModel @ViewModelInject constructor(
    private val loginUseCase: LoginUseCase
) : ViewModel() {

    val currentResult: MutableLiveData<String> by lazy {
        MutableLiveData<String>()
    }

    fun loginUseCase(username: String, password: String) {
        viewModelScope.launch {
            loginUseCase.invoke(username, password).apiKey.let {
                currentResult.value = it
            }
        }
    }

}

正在被我的 MainActivity 使用:

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {

    private val loginViewModel: LoginViewModel by viewModels()

而且我知道 ViewModelProvider 需要一个空的构造函数,但我需要使用 LoginUseCase:

class LoginUseCase @Inject constructor(
    private val apiService: ApiServiceImpl
) : UseCase<Unit>() {
    suspend operator fun invoke(username: String, password: String) =
        apiService.login(username, password)
}

在modelView里面,但是我得到了错误:

无法创建 com.example.myboards.ui.login.LoginViewModel 类的实例

在运行时,我不知道如何管理 LoginViewModel 中的 LoginUseCase

【问题讨论】:

  • 我猜这与应用程序 build.gradle 文件中的依赖关系有关。请分享build.gradle 依赖项

标签: android kotlin android-viewmodel use-case dagger-hilt


【解决方案1】:

通过使用@HiltViewModel 注释它并在ViewModel 对象的构造函数中使用@Inject 注释来提供ViewModel

@HiltViewModel
class LoginViewModel @Inject constructor(
  private val loginUseCase: LoginUseCase
) : ViewModel() {
  ...
}

Hilt 也需要知道如何提供 ApiServiceImpl 的实例。阅读here,了解如何使用@Binds 注入接口实例。

如果您仍有问题,请告诉我。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2022-07-20
  • 2021-11-28
  • 2017-12-13
  • 1970-01-01
  • 2021-07-20
相关资源
最近更新 更多