Search code examples
androidkotlinandroid-viewmodeluse-casedagger-hilt

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


Solution

  • 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.