Android Hilt Viewmodel
In this tutorial, you'll learn about Android Hilt ViewModel. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Problem
Your @HiltViewModel doesn't inject dependencies, or you get java.lang.RuntimeException: Cannot create an instance of class YourViewModel.
Wrong Approach ❌
// No @HiltViewModel annotation
class BadViewModel(
private val repo: UserRepository
) : ViewModel() {
// repo is always null — no injection
}
// Manual factory — defeating Hilt's purpose
@AndroidEntryPoint
class MyActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val vm = ViewModelProvider(this, MyViewModelFactory(repo)).get(MyViewModel::class.java)
}
}
Output: Cannot create an instance of ViewModel or manual Factory boilerplate.
Right Approach ✅
@HiltViewModel
class GoodViewModel @Inject constructor(
private val userRepository: UserRepository,
private val savedStateHandle: SavedStateHandle
) : ViewModel() {
val userId: String = savedStateHandle.get<String>("userId") ?: ""
val users: StateFlow<List<User>> = userRepository.users
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())
fun loadUser(id: String) {
viewModelScope.launch {
userRepository.getUser(id)
}
}
}
// In Activity/Fragment — Hilt injects automatically
@AndroidEntryPoint
class UserActivity : AppCompatActivity() {
private val viewModel: GoodViewModel by viewModels() // No factory needed!
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel.loadUser("123")
}
}
Output: Hilt automatically creates ViewModel with all dependencies injected.
Prevention
- Always annotate ViewModel with
@HiltViewModel+@Inject constructor. - Use
by viewModels()orhiltViewModel()for instantiation. - Use
SavedStateHandlefor navigation arguments. - Never manually create ViewModel instances.
Common Mistakes with hilt viewmodel
- Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
These mistakes appear frequently in real-world Android code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro