Thuta Learning
AdvancedMobile Developmentintermediate

Dependency Injection (Hilt)

Relax. We'll talk through this in plain words — no textbook voice.

What you'll walk away with

  • Understand Dependency Injection (Hilt) without the intimidation
  • Get comfortable running Android Studio/Compose code yourself
  • Apply this concept in a real project right away

Let's think about it this way for a second

Dependency Injection (DI) is a pattern where a class doesn't create its own dependencies but instead has them handed to it from the outside — this improves testing/maintainability (since you can inject fake dependencies for tests). Hilt is Google's official Android DI library — just put the `@Inject` annotation on a constructor, and Hilt automatically creates/provides the dependencies (Retrofit, Room database) for you — no more writing `Retrofit.Builder()...build()` by hand in every single ViewModel.

Let's connect this to a real scenario

If you write `@HiltViewModel class TodoViewModel @Inject constructor(private val dao: TodoDao) : ViewModel() { ... }` — Hilt automatically creates/injects the `TodoDao` instance, so you never need to manually pass a dao parameter into `TodoViewModel()` (you get it straight from the `viewModel()` Composable function).

Let's walk through it together

kotlin
@HiltViewModel
class TodoViewModel @Inject constructor(
    private val dao: TodoDao,
    private val weatherApi: WeatherApi
) : ViewModel() {
    // dao and weatherApi are automatically provided by Hilt —
    // no manual Retrofit.Builder()/Room.databaseBuilder() calls here
}

@Composable
fun TodoScreen(viewModel: TodoViewModel = hiltViewModel()) {
    // ...
}
You should see
Grabbing TodoViewModel from hiltViewModel() should have dao/weatherApi ready to go without any manual passing.

5-minute try-it

Read through the Hilt setup docs (`@HiltAndroidApp`, `@Module`, `@Provides` annotations) and sketch out how you'd provide `TodoDao`/`WeatherApi` as a Hilt module.

A quick word of caution

Hilt's annotation processing can slow down your build time a bit — keep in mind that the complexity of Hilt setup can be overkill for a small (learning) project.

Easy traps

  • Forgetting to add the `@HiltAndroidApp` annotation on the Application class — your entire Hilt setup won't work
  • Forcing Hilt onto a small app (just 2-3 screens) — with few dependencies, manual injection can be simpler and more fitting

Now try it yourself

Read through the Hilt setup docs (`@HiltAndroidApp`, `@Module`, `@Provides` annotations) and sketch out how you'd provide `TodoDao`/`WeatherApi` as a Hilt module.

You'll know it worked when: Grabbing TodoViewModel from hiltViewModel() should have dao/weatherApi ready to go without any manual passing.

Dependency Injection (Hilt) | Thuta Learning