我的视图模型:
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
答案 0 :(得分:0)
通过使用 ViewModel
注释并在 @HiltViewModel
对象的构造函数中使用 @Inject
注释来提供 ViewModel
。
@HiltViewModel
class LoginViewModel @Inject constructor(
private val loginUseCase: LoginUseCase
) : ViewModel() {
...
}
Hilt 也需要知道如何提供 ApiServiceImpl 的实例。阅读 here 以了解如何使用 @Binds
注入接口实例。
如果您仍有问题,请告诉我。