简体   繁体   中英

Cannot create an instance of class ViewModel using dagger hilt

My ViewModel:

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
            }
        }
    }

}

Is being used by my MainActivity:

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {

    private val loginViewModel: LoginViewModel by viewModels()

And I know that the ViewModelProvider is expecting a empty constructor but I need to use the LoginUseCase:

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

Inside the modelView, but i get the error:

Cannot create an instance of class com.example.myboards.ui.login.LoginViewModel

in runtime, and I dont know how I could manage the LoginUseCase inside the LoginViewModel

Provide a ViewModel by annotating it with @HiltViewModel and using the @Inject annotation in the ViewModel object's constructor.

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

Hilt needs to know how to provide instances of ApiServiceImpl, too. Read here to know how to inject interface instances with @Binds .

Let me know If you still have a problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM