Hilt

Android Development with Compose: Architecture & Data

Course 5 ยท Chapter 10 ยท Letting a Library Do the Wiring

Chapter 9 hand-wrote an AppContainer and a ViewModel factory. Hilt is Android's dependency injection library: you mark what exists and what is needed with annotations, and Hilt generates the container and the factories at build time. Everything from Chapter 9 still applies: constructor injection, fakes in tests. Hilt just removes the typing.

What was checked, and how: read this first
Checked in the docs (one search, summaries only): Hilt now supports KSP and the compiler dependency goes in the ksp configuration; the Hilt Gradle plugin is declared in the root build file with apply false and applied in each module, together with the KSP plugin; the Dagger docs listed Hilt 2.60.1 and the Android guide 2.57.1 (so versions here are placeholders); the docs name the compiler artifact hilt-android-compiler in one snippet and hilt-compiler in another, so check which your version uses; hiltViewModel() retrieves a ViewModel scoped to the current navigation destination, with androidx.hilt:hilt-lifecycle-viewmodel-compose (1.3.0 in the guide); testing needs hilt-android-testing and compilers on the test configurations; and the module that compiles your Application class needs all Hilt modules and injected classes in its dependencies. The search did not cover the annotations in depth. @Provides, @Binds, @InstallIn, @Singleton, @HiltViewModel and @Inject as written below are general knowledge, apart from one older deprecated codelab that used SingletonComponent. All code is unrun (no Kotlin compiler on the machine used to write this); nothing was seen on your install.

What Hilt Replaces

Chapter 9 (by hand)Hilt
DefaultAppContainer building each objectModules with @Provides and @Binds, plus @Inject constructors
NotesApp creating the container@HiltAndroidApp on NotesApp
by lazy for one instance@Singleton
AppViewModelProvider factory@HiltViewModel and hiltViewModel() (docs: Hilt generates the factory)
Wiring mistakes found at first useMissing bindings reported when the app is built (general knowledge)

Setup

// Root build.gradle.kts (versions are placeholders; take current ones from the Hilt docs) plugins { id("com.google.dagger.hilt.android") version "<hilt-version>" apply false id("com.google.devtools.ksp") version "<ksp-version>" apply false }
// Module build.gradle.kts plugins { id("com.google.devtools.ksp") id("com.google.dagger.hilt.android") } dependencies { implementation("com.google.dagger:hilt-android:<hilt-version>") ksp("com.google.dagger:hilt-compiler:<hilt-version>") // the docs also show the name hilt-android-compiler implementation("androidx.hilt:hilt-lifecycle-viewmodel-compose:<androidx-hilt-version>") // for hiltViewModel() }
  • (docs) The plugin is declared at the root with apply false and applied in each module; the compiler goes through ksp. Room in Chapter 4 already needed KSP, so the plugin is probably already there.
  • (docs) Older setups used kapt, which needs extra settings; avoid it in a new project.
  • (docs, unresolved) Compiler artifact name: hilt-compiler or hilt-android-compiler. Take the one the current Hilt setup page for your version shows.
  • Versions: take current ones from the Hilt release notes. The two docs pages above disagreed, which is a sign they are updated often.

The Entry Points

import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class NotesApp : Application() // the container, onCreate and lateinit are gone
import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : ComponentActivity() { // onCreate and setContent as before }

(general knowledge) @HiltAndroidApp tells Hilt to build the app-wide set of objects (the "container" of Chapter 9, generated). @AndroidEntryPoint lets an Activity (or Fragment) receive injected objects; here it also makes hiltViewModel() work for composables inside it.

A ViewModel Hilt Can Build

import androidx.lifecycle.ViewModel import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject @HiltViewModel class NotesViewModel @Inject constructor( private val repository: NotesRepository, private val settings: SettingsRepository ) : ViewModel() { // the body is unchanged; the companion object Factory is gone }
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel // check the exact package in the IDE @Composable fun NotesRoute(viewModel: NotesViewModel = hiltViewModel()) { // ...as before }

(docs) hiltViewModel() retrieves a ViewModel scoped to the current navigation destination, using the androidx.hilt Compose artifact. (general knowledge) The ViewModel's constructor now carries @Inject and the class @HiltViewModel; the factory, AppViewModelProvider and the default-argument viewModel(factory = ...) are all gone. The package of hiltViewModel has moved over time, so use the IDE's import suggestion rather than trusting the line above.

Telling Hilt How to Build Things

Classes you own can say "Hilt, you may construct me" with an @Inject constructor:

import javax.inject.Inject import javax.inject.Singleton @Singleton class DefaultNotesRepository @Inject constructor( private val noteDao: NoteDao, private val api: NotesApi ) : NotesRepository { // unchanged } @Singleton class SettingsRepository @Inject constructor( private val dataStore: DataStore<Preferences> ) { // unchanged }

(general knowledge) @Singleton means one instance for the whole app, the job by lazy did in Chapter 9. Hilt can build DefaultNotesRepository because it can build or provide each constructor parameter. For the rest, you write a module:

import android.content.Context import dagger.Binds import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import javax.inject.Singleton // @Provides: for things you cannot (or do not want to) construct with @Inject @Module @InstallIn(SingletonComponent::class) object DataModule { @Provides @Singleton fun provideDatabase(@ApplicationContext context: Context): AppDatabase = Room.databaseBuilder(context, AppDatabase::class.java, "notes.db").build() @Provides fun provideNoteDao(database: AppDatabase): NoteDao = database.noteDao() @Provides @Singleton fun provideDataStore(@ApplicationContext context: Context): DataStore<Preferences> = context.settingsDataStore @Provides @Singleton fun provideNotesApi(): NotesApi = Retrofit.Builder() .baseUrl("https://jsonplaceholder.typicode.com/") .addConverterFactory(json.asConverterFactory("application/json".toMediaType())) .build() .create(NotesApi::class.java) } // @Binds: "when someone asks for the interface, give them this implementation" @Module @InstallIn(SingletonComponent::class) abstract class RepositoryModule { @Binds abstract fun bindNotesRepository(impl: DefaultNotesRepository): NotesRepository }
  • @Provides (general knowledge) is for objects you cannot put @Inject on: a Room database, a Retrofit service, a DataStore. The function body is the recipe; its parameters are more dependencies Hilt supplies.
  • @Binds (general knowledge) says which implementation to use when someone asks for an interface: NotesRepository gets DefaultNotesRepository. This is how Chapter 5's interface choice becomes configuration, and where a test could swap in a fake.
  • @InstallIn(SingletonComponent::class) (general knowledge, and in an older deprecated codelab) says these bindings live for the whole app.
  • @ApplicationContext (general knowledge) asks Hilt for the application Context, which a long-lived object should use rather than an Activity.

That is the whole of DefaultAppContainer, moved into annotations. Delete AppContainer, DefaultAppContainer, AppViewModelProvider and the old NotesApp body.

Testing

// The unit test is unchanged: constructor injection means no Hilt is needed to build the ViewModel val viewModel = NotesViewModel(FakeNotesRepository(), FakeSettingsRepository())

(docs) Tests that use Hilt itself need hilt-android-testing and a compiler on the test configurations (kspTest, kspAndroidTest), plus a test Activity annotated with @AndroidEntryPoint. (general knowledge) But the ViewModel unit test from Chapters 5 and 9 does not change: it builds the ViewModel directly with fakes. That is the benefit of constructor injection first.

Manual DI or Hilt?

Manual (Chapter 9)Hilt
Code to writeA container and a factory that grow with the appAnnotations and a few modules
MagicNone: you can read every lineGenerated code; errors can be harder to read (general knowledge)
SetupNonePlugin, KSP, versions to keep in step
FitsSmall apps (docs: manual DI or Hilt for simple apps)Apps with many classes and screens; the Catalogue project course uses it

There is no right answer for a notes app. The honest summary of the docs is that both are acceptable for simple apps, and Hilt earns its setup as the dependency graph grows.

Compared with the Classic UI course
Android Development: Architecture & Data 5 teaches why dependency injection helps, Hilt setup, modules and injecting into a ViewModel. The same ground, in a different order: this course did the manual version first (Chapter 9) and then Hilt, and uses hiltViewModel() in Compose in place of by viewModels(), and KSP in place of kapt.

Try It Yourself

Exercise 1

Convert the app from Chapter 9's container to Hilt: add the plugins and dependencies, annotate NotesApp, MainActivity and the ViewModel, write the modules, and delete the container and factory. Report the Hilt, KSP and compiler artifact names and versions you used, and any build error.

๐Ÿ“„ View solution
Exercise 2

Provide the Json instance from a module and use it in provideNotesApi. Then bind a second interface (the TimeProvider from Chapter 9, Exercise 2) with @Binds. Explain when you need @Provides and when @Binds is enough.

๐Ÿ“„ View solution
Exercise 3

Break it on purpose: remove the @Binds function, then restore it and remove @AndroidEntryPoint from MainActivity. Write down what each error says and whether it appeared at build time or at run time. Then say which approach, Chapter 9's or Hilt, you would choose for this app, and why.

๐Ÿ“„ View solution
Not Yet Verified
Checked in the docs (one search, summaries only): KSP support and the ksp configuration; the root apply false plugin declaration applied in each module; versions 2.60.1 (Dagger docs) and 2.57.1 (Android guide); the compiler artifact name discrepancy; hiltViewModel() scoped to a navigation destination and the androidx.hilt Compose artifact; Hilt generating the ViewModel factory; the testing artifacts and configurations; the module that compiles Application needing all Hilt modules in its dependencies; kapt needing extra settings.
General knowledge, not checked: @HiltAndroidApp, @AndroidEntryPoint, @HiltViewModel, @Inject, @Singleton, @Provides, @Binds, @ApplicationContext and @InstallIn as written (only SingletonComponent appeared in an old deprecated codelab); the hiltViewModel import package; build-time reporting of missing bindings; the comparison table.
Not verified: every listing and solution (unrun); the exercises (not run by me). Nothing was checked on your install.
Sources: Dependency injection with Hilt (developer.android.com), Use Hilt with other Jetpack libraries (developer.android.com), Hilt Gradle build setup (dagger.dev), Dagger KSP (dagger.dev), Hilt testing guide (developer.android.com), Hilt releases (developer.android.com), Using Hilt in your Android app codelab (developer.android.com, deprecated).
Coming up
Chapter 11 is the capstone: a small notes app that uses everything in this course, with a checklist to build it from.