With Hilt, how does an Android screen obtain a @HiltViewModel, and why is injecting that ViewModel into an @Inject field rejected?
answer
- constructor injection plus an annotation
- Hilt's default ViewModel factory
- by viewModels() or hiltViewModel()
- one instance per ViewModelStore
- ViewModelComponent's parent
basics
~20 sAnnotate the ViewModel with @HiltViewModel and an @Inject constructor, then request it through the ViewModel APIs: by viewModels() in an @AndroidEntryPoint activity or fragment, or hiltViewModel() in Compose. Field injection fails the build because it bypasses the ViewModelStore.
solid answer
~40 sA Hilt ViewModel is a Jetpack `ViewModel` with `@HiltViewModel` on the class and an `@Inject` constructor listing its dependencies, such as a repository and the `SavedStateHandle`. An `@AndroidEntryPoint` activity or fragment uses Hilt's factory as its default ViewModel factory, so the screen just writes `by viewModels()` or `ViewModelProvider(this).get(...)`; in Compose, `hiltViewModel()` does the same for the current destination. You never inject the ViewModel itself: Hilt fails the build if you request it from the graph, because each injection would build a fresh instance that the `ViewModelStore` does not hold, so it would not survive rotation. Its dependencies come from `ViewModelComponent`, whose parent is `ActivityRetainedComponent`, so a ViewModel can never receive an `Activity` or `@ActivityContext`.
code
kotlin · 13 lines@HiltViewModel
class HeadlinesViewModel @Inject constructor(
savedStateHandle: SavedStateHandle,
private val repository: NewsRepository
) : ViewModel() {
val section: String = savedStateHandle.get<String>("section") ?: "top"
}
@AndroidEntryPoint
class HeadlinesFragment : Fragment() {
// Hilt's factory is the fragment's default ViewModel factory
private val viewModel: HeadlinesViewModel by viewModels()
}go deeper
Recall the two annotations on the ViewModel, and that a screen gets it with by viewModels() or hiltViewModel(), never with @Inject.
Explain Hilt's default factory, why direct injection breaks ViewModel identity, and which component and default bindings a ViewModel's constructor can draw from.
Choose between SavedStateHandle and assisted injection for runtime arguments, and spot constructor parameters that would leak a screen.
Decide how far a codebase leans on Hilt ViewModels versus plain constructors, keeping ViewModels testable by direct construction with fakes.
## What `@HiltViewModel` declares A **Hilt ViewModel** is an ordinary Jetpack `ViewModel` that Hilt constructs for you. You put **`@HiltViewModel`** on the class and **`@Inject`** on its constructor. The constructor's parameters, such as a `NewsRepository` and the `SavedStateHandle`, are resolved from Hilt's graph. The ViewModel's lifecycle itself is the Jetpack library's business; what Hilt adds is how the instance is built. ## How a screen obtains one The rule is that a ViewModel is always obtained through the **ViewModel APIs**, which consult the owner's `ViewModelStore` first and only create a new instance when none is stored. - In an **`@AndroidEntryPoint` activity or fragment**, Hilt installs its own factory as the default ViewModel factory, so `private val viewModel: HeadlinesViewModel by viewModels()` or `ViewModelProvider(this).get(HeadlinesViewModel::class.java)` returns a Hilt-built instance. - A fragment can share its activity's instance with `by activityViewModels()`; that uses the activity's factory, so the activity must be a Hilt activity too. - In **Compose**, call `hiltViewModel()` inside a destination; an AndroidX Hilt Compose artifact provides it (the Jetpack guides name `hilt-lifecycle-viewmodel-compose` and `hilt-navigation-compose`, versioned separately from Hilt), and the ViewModel is scoped to the navigation destination. - If the owner is **not** a Hilt entry point, the default factory cannot call a constructor that takes your repository, and the lookup fails at runtime. ## Why `@Inject lateinit var viewModel` is rejected The ViewModel has an `@Inject` constructor, so it looks injectable. Hilt nevertheless checks at compile time that nobody requests it from the graph, and fails the build if they do. The reason is identity: an injected ViewModel would be a **new object per injection**, never stored in the `ViewModelStore`. It would not survive a configuration change, two fragments could not share it, and `onCleared()` would never be called for it. The same compile-time rule applies to the assisted factory of a ViewModel that uses assisted injection. ## What a Hilt ViewModel can depend on Hilt injects every ViewModel from **`ViewModelComponent`**, created when the ViewModel is created and destroyed when it is cleared. Its parent is **`ActivityRetainedComponent`**, whose parent is `SingletonComponent`. | Available to a ViewModel | Not available | |---|---| | `SavedStateHandle`, `ViewModelLifecycle` (defaults of `ViewModelComponent`) | `Activity`, `Fragment` | | `@ViewModelScoped`, `@ActivityRetainedScoped`, `@Singleton` and unscoped bindings | `@ActivityContext Context` | | `Application` and `@ApplicationContext Context` | anything installed only in `ActivityComponent` or below | This is deliberate: a ViewModel outlives each activity instance across rotation, so holding an activity would leak it. The graph makes that impossible to wire by accident. **`@ViewModelScoped`** shares one instance across every dependency **inside one ViewModel**: if two helper classes of `HeadlinesViewModel` both take a `@ViewModelScoped` cache, they get the same cache, while a second ViewModel gets its own. To share across ViewModels, scope it with `@ActivityRetainedScoped` or `@Singleton` instead. ## Runtime arguments: `SavedStateHandle` or assisted injection Two ways exist to give a ViewModel a value only known at runtime, such as an article ID. 1. Read it from **`SavedStateHandle`**, which carries navigation arguments and survives process death. 2. Use **assisted injection**: `@HiltViewModel(assistedFactory = ...)`, an `@AssistedInject` constructor with `@Assisted` parameters, and an `@AssistedFactory` interface. The screen supplies the value through `withCreationCallback` on the creation extras. ```kotlin @HiltViewModel(assistedFactory = ArticleViewModel.Factory::class) class ArticleViewModel @AssistedInject constructor( @Assisted val articleId: String, private val repository: NewsRepository ) : ViewModel() { @AssistedFactory interface Factory { fun create(articleId: String): ArticleViewModel } } ``` Assisted values are **not saved**: after process death they are gone, and because the ViewModel is memoized by its owner, the callback is ignored while an instance exists, so a later call cannot change the argument. Hilt's documentation also warns never to pass an `Activity`, `Fragment` or `View` through the factory, since that leaks it. ## Testing a Hilt ViewModel Because the dependencies arrive through the constructor, a Hilt ViewModel needs **no Hilt at all in a unit test**: - Construct it directly, passing a fake `NewsRepository` and a `SavedStateHandle` built with the values the test needs. - The `@HiltViewModel` annotation only matters when the ViewModel is obtained through the ViewModel APIs inside a Hilt entry point. - In a UI test that launches a real screen, you do not replace the ViewModel either. You replace the **binding it depends on**, for example by swapping the module that provides the repository with a test module; the screen's `hiltViewModel()` or `by viewModels()` then builds the ViewModel around the fake automatically. This is also a design check: if a ViewModel is hard to construct by hand, it is probably reaching for something it should receive through its constructor. ## Common mistakes - Field-injecting the ViewModel, or its assisted factory, instead of using the ViewModel APIs. - Calling `by viewModels()` in an activity that is not `@AndroidEntryPoint`. - Requesting an `@ActivityContext Context` in the constructor; use `@ApplicationContext` or move that work to the UI. - Expecting `@ViewModelScoped` to share an instance between two different ViewModels.
- Two helper classes inside one ViewModel need the same in-memory cache; how do you scope it?Install the cache's binding in `ViewModelComponent` and annotate it `@ViewModelScoped`. Every dependency of that one ViewModel instance then shares a single cache, while another ViewModel gets its own. It is created and dropped with the ViewModel, which also survives rotation.
- When would you choose assisted injection over SavedStateHandle for a ViewModel argument?When the value is not something you can put in saved state, such as a non-Parcelable object, and losing it after process death is acceptable or recoverable. For a navigation argument like an article ID, `SavedStateHandle` is usually better, because it is restored after process death.
- A @HiltViewModel can be field-injected with @Inject lateinit var like any class.
- A Hilt ViewModel can take an @ActivityContext Context in its constructor.
- @ViewModelScoped shares one instance among all ViewModels of the activity.
- by viewModels() returns a Hilt ViewModel even in a non-Hilt activity.
- Assisted ViewModel arguments are restored after process death like SavedStateHandle.
- Calling the assisted creation callback again replaces the argument in the existing ViewModel.