Injecting into ViewModels
Use @HiltViewModel for clean injection.
Injecting ViewModels with Hilt
ViewModels are special: the framework instantiates them via a factory. Hilt integrates with this through the @HiltViewModel annotation.
Annotating the ViewModel
Mark the ViewModel with @HiltViewModel and annotate its constructor with @Inject.
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class UserViewModel @Inject constructor(
private val repo: UserRepository
) : ViewModel()All lessons in this course
- Why Dependency Injection?
- Setting Up Hilt
- Modules and Providers
- Injecting into ViewModels