tezvyn:

@HiltViewModel: Simplified ViewModel Injection

AI-drafted, machine-checkedSource: developer.android.comintermediate
@HiltViewModel: Simplified ViewModel Injection

@HiltViewModel automates creating ViewModels with dependencies. Instead of writing custom factories, just annotate the ViewModel and its constructor. It's the standard for injecting dependencies like repositories into ViewModels in a Hilt-powered Android app.

WHY IT EXISTS Manually creating Android ViewModels that have dependencies (like a repository or use case) requires writing a custom ViewModelProvider.Factory. This is boilerplate code that is repetitive, tedious, and error-prone. Hilt was designed to eliminate this manual setup.

THE MENTAL MODEL Think of @HiltViewModel as a contract with the Hilt dependency injection framework. You are telling Hilt: "You are responsible for creating this ViewModel. I will tell you what it needs in its constructor, and you figure out how to provide those things and build the necessary factory for me."

HOW IT WORKS When you annotate a ViewModel class with @HiltViewModel, Hilt's code generator creates a special factory for it behind the scenes. You must also provide an @Inject-annotated constructor so Hilt knows what dependencies to supply. Then, in an Activity or Fragment annotated with @AndroidEntryPoint, you can request the ViewModel as usual (e.g., using the by viewModels() Kotlin property delegate). Hilt intercepts this request, uses its generated factory to create the ViewModel instance, and provides all the necessary dependencies from its dependency graph.

WHEN TO USE IT Use @HiltViewModel for every ViewModel that has dependencies in an application that uses Hilt for dependency injection. It is the standard, idiomatic way to integrate ViewModels into the Hilt ecosystem.

WHEN NOT TO USE IT Don't use it if your project does not use Hilt for dependency injection. In very rare, complex scenarios, you might need a custom factory for dynamic dependency creation that falls outside Hilt's standard capabilities, but this is highly uncommon. For nearly all cases in a Hilt project, @HiltViewModel is the correct choice.

ONE CANONICAL EXAMPLE To create a ProfileViewModel that depends on a UserRepository, you would define the ViewModel like this: class ProfileViewModel @Inject constructor(private val userRepository: UserRepository) : ViewModel() { ... }. You must annotate the class with @HiltViewModel. Then, in your Fragment, you annotate the Fragment class with @AndroidEntryPoint and get the ViewModel simply by declaring private val viewModel: ProfileViewModel by viewModels(). Hilt handles the injection of UserRepository automatically.

Read the original → developer.android.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.