Is field injection not allowed in viewmodels?

Viewed 461

I am new to Dependency Injection in Android, and I am trying to apply it in my app using Hilt. I have a viewmodel annotated with @HiltViewModel and I'm trying to field inject a repository using the @Inject annotation. But I keep getting this error:

public final class AlarmsViewModel extends androidx.lifecycle.ViewModel {
             ^
  @HiltViewModel annotated class should contain exactly one @Inject annotated constructor.
  [Hilt] Processing did not complete. See error above for details.

This is my viewmodel:

@HiltViewModel
class AlarmsViewModel : ViewModel() {
    var alarmsLiveData = MutableLiveData<MutableList<Alarm>>()
    var alarmFormLiveData = MutableLiveData<Alarm>()
    @Inject lateinit var alarmsRepository: AlarmsRepository

    init {
        alarmFormLiveData.value = Alarm()
    }

    fun save() {
        viewModelScope.launch {
            alarmsRepository.save(alarmFormLiveData.value!!)
        }
    }
}

This is the repostory I want to inject:

class AlarmsRepository @Inject constructor(
    private val alarmDao: AlarmDao
) {
    suspend fun load(): Flow<List<Alarm>> {
        return alarmDao.load()
    }

    suspend fun save(alarm: Alarm) {
        alarmDao.save(alarm)
    }
}

What do you think I am doing wrong? Maybe I misunderstood something. Also the version of hilt I am using is 2.37

2 Answers

as error says "@HiltViewModel annotated class should contain exactly one @Inject annotated constructor."

your AlarmsViewModel is missing one

replace :

@HiltViewModel
class AlarmsViewModel : ViewModel()

with :

@HiltViewModel
class AlarmsViewModel @Inject constructor(var alarmsRepository: AlarmsRepository) : ViewModel()

and remove

@Inject lateinit var alarmsRepository: AlarmsRepository
Related