0Pricing
Android Academy · Lesson

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

  1. Why Dependency Injection?
  2. Setting Up Hilt
  3. Modules and Providers
  4. Injecting into ViewModels
← Back to Android Academy