Skip to content

Android Hilt Viewmodel

DodaTech 2 min read

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() or hiltViewModel() for instantiation.
  • Use SavedStateHandle for navigation arguments.
  • Never manually create ViewModel instances.

Common Mistakes with hilt viewmodel

  1. Mixing let bindings with <- bindings in do notation, producing type errors
  2. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  3. 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

### What is SavedStateHandle in ViewModel?

It's a handle that survives Process death. Use it in the @Inject constructor to get navigation arguments and other saved state. Works like Bundle in onSaveInstanceState.

### How do I inject a ViewModel in Compose?

Use val viewModel: MyViewModel = hiltViewModel() in a Composable. The ViewModel is scoped to the nearest @AndroidEntryPoint or navigation destination.

### What is assisted injection in Hilt?

With Hilt's @AssistedInject, you pass runtime parameters alongside injected dependencies. Useful for ViewModels that need dynamic IDs. Use @Assisted annotation on constructor params.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro