Hilt scopes and components
Why it matters
- Choosing the wrong scope causes memory leaks (a
@Singletonholding an Activity) or stale state (per-user data in an app-wide object that survives logout). - Interviewers ask you to trace a dependency through the component tree and explain why it lives or dies at a given point.
- Scope annotations are checked at build time: an
@ActivityScopedclass injected into a ViewModel fails the build, and knowing the tree tells you why. - Scoping is not free. Knowing what it costs stops the "just make it
@Singleton" habit.
The simple explanation
- Think of a company building. SingletonComponent is the building itself: it exists as long as the business runs.
- ActivityComponent is a floor: it exists while you are on that floor, gone when you leave. FragmentComponent is a desk on that floor.
- A desk can use the building's power supply (a singleton), but the power supply cannot depend on a specific desk.
- Unscoped means a new object every time someone asks for it, like a disposable coffee cup.
Hilt generates a component tree at compile time. Each component is a Dagger component that owns a set of bindings and has a lifetime tied to an Android class. Each has one matching scope annotation:
| Component | Scope annotation | Parent | Lives from / to |
|---|---|---|---|
SingletonComponent | @Singleton | none (root) | Application#onCreate() until the process dies |
ActivityRetainedComponent | @ActivityRetainedScoped | SingletonComponent | First Activity#onCreate() to the final onDestroy(); survives configuration changes |
ViewModelComponent | @ViewModelScoped | ActivityRetainedComponent | ViewModel created to ViewModel cleared |
ActivityComponent | @ActivityScoped | ActivityRetainedComponent | Activity#onCreate() to onDestroy(); recreated on rotation |
FragmentComponent | @FragmentScoped | ActivityComponent | Fragment#onAttach() to onDestroy() |
ViewComponent | @ViewScoped | ActivityComponent | View created to destroyed |
ViewWithFragmentComponent | @ViewScoped | FragmentComponent | View created to destroyed (Views with @WithFragmentBindings) |
ServiceComponent | @ServiceScoped | SingletonComponent | Service#onCreate() to onDestroy() |
Visibility. A child component can inject anything its ancestors provide; a parent can never see a child's bindings. ViewModelComponent hangs off ActivityRetainedComponent, not ActivityComponent, so a ViewModel cannot inject the Activity or an @ActivityScoped object (that would leak it across rotation). The build fails if you try.
Scope must match the component. A scope annotation on a class or @Provides method must be the one for the component the binding is installed in (or reachable from). An @ActivityScoped binding in a SingletonComponent module is a build error.
Unscoped (no annotation) means a new instance every time the binding is requested, in any component. That is the default and is right for cheap, stateless objects.
What scoping costs. A scoped binding is wrapped so the first instance is cached (for @Singleton, behind a double-checked lock), and it stays in memory for the component's whole lifetime. Scoping a large object to SingletonComponent holds it for the life of the process, and any state in it is shared by every screen and every user session. Scope an object when it is expensive to create, or when sharing one instance is the point (a cache, a connection, an in-memory session).
Default bindings come free in each component: Application everywhere (with @ApplicationContext), the Activity in ActivityComponent and below (with @ActivityContext), the Fragment in FragmentComponent, and SavedStateHandle and ViewModelLifecycle in ViewModelComponent. ActivityRetainedLifecycle lets an @ActivityRetainedScoped object register addOnClearedListener to release resources.
Notes
- Hierarchy:
SingletonComponent→ActivityRetainedComponent→ (ViewModelComponent,ActivityComponent→ (FragmentComponent→ViewWithFragmentComponent,ViewComponent));ServiceComponentsits directly underSingletonComponent. - A child can use parent bindings, never the reverse. A ViewModel can use
@Singletonand@ActivityRetainedScopedbindings, but not@ActivityScopedones or theActivityitself. @Singletonmeans one instance perSingletonComponent, which is one per process. Unlike a Kotlinobject, Hilt creates it, and a test can replace its binding.- Unscoped produces a new instance per request. A scope on a class only works if the class has an
@Injectconstructor or the scope is on its@Provides/@Bindsmethod. - Installing a module in
SingletonComponentdoes not make its bindings singletons; only@Singletondoes. @ActivityRetainedScopedsurvives configuration changes and is released when the Activity finishes. It does not survive process death; nothing in memory does.@ViewModelScopedshares one instance among all the dependencies of one ViewModel (for example a use case and a repository wrapper that both need the same in-memory state). Two different ViewModels get two instances.- Assisted-injected types (
@AssistedInject) cannot be scoped; each call to the factory creates a new instance. - To release resources when a component ends, use
ActivityRetainedLifecycle.addOnClearedListenerorViewModelLifecycle.addOnClearedListener. Hilt does not callclose()on scoped objects for you. - Testing:
@TestInstallInreplaces a module for the whole test source set,@UninstallModulesplus a nested@InstallInmodule replaces it for one class, and@BindValuebinds a field of the test itself.
Code example
A @Singleton repository with an in-memory cache, an @ActivityRetainedScoped object that releases its socket when the Activity is truly finished, and a @ViewModelScoped object shared by two dependencies of one ViewModel.
import androidx.lifecycle.ViewModel
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.ActivityRetainedLifecycle
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.scopes.ActivityRetainedScoped
import dagger.hilt.android.scopes.ViewModelScoped
import dagger.hilt.components.SingletonComponent
import javax.inject.Inject
import javax.inject.Singleton
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import retrofit2.Retrofit
import retrofit2.converter.scalars.ScalarsConverterFactory
import retrofit2.http.GET
import retrofit2.http.Path
interface UserApi {
@GET("users/{id}/name")
suspend fun name(@Path("id") id: String): String
}
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
@Provides
@Singleton // expensive and shareable: one per process
fun provideOkHttp(): OkHttpClient = OkHttpClient()
@Provides
@Singleton
fun provideUserApi(client: OkHttpClient): UserApi =
Retrofit.Builder()
.baseUrl("https://api.example.com/") // must end with '/'
.client(client)
.addConverterFactory(ScalarsConverterFactory.create())
.build()
.create(UserApi::class.java)
}
// Shared cache, so @Singleton is the point
@Singleton
class UserRepository @Inject constructor(private val api: UserApi) {
private val mutex = Mutex()
private val names = mutableMapOf<String, String>()
suspend fun name(id: String): String = mutex.withLock {
names.getOrPut(id) { api.name(id) }
}
suspend fun clear() = mutex.withLock { names.clear() } // call on logout
}
// Survives rotation; closed when the Activity finishes for good
@ActivityRetainedScoped
class LiveUpdates @Inject constructor(
client: OkHttpClient,
lifecycle: ActivityRetainedLifecycle,
) {
private val socket: WebSocket =
client.newWebSocket(Request.Builder().url("wss://api.example.com/live").build(), object : WebSocketListener() {})
init {
lifecycle.addOnClearedListener { socket.close(1000, "screen finished") }
}
}
// One instance per ViewModel, shared by everything that ViewModel injects
@ViewModelScoped
class SelectionState @Inject constructor() {
val selectedId = MutableStateFlow<String?>(null)
}
class SelectItem @Inject constructor(private val state: SelectionState) {
operator fun invoke(id: String) { state.selectedId.value = id }
}
@HiltViewModel
class ProfileViewModel @Inject constructor(
val repository: UserRepository,
val liveUpdates: LiveUpdates,
val selectItem: SelectItem,
state: SelectionState, // the same instance SelectItem received
) : ViewModel() {
val selectedId: StateFlow<String?> = state.selectedId
}OkHttpClient,UserApiandUserRepositoryare@Singletonbecause they are expensive or hold a cache that every screen should share. The repository'sclear()exists because a process-wide cache outlives a user session.LiveUpdatesis@ActivityRetainedScoped: rotation does not reconnect the socket, andaddOnClearedListenercloses it when the Activity finishes. The ViewModel can inject it becauseViewModelComponentis a child ofActivityRetainedComponent.SelectionStateis@ViewModelScoped, soSelectItemandProfileViewModelsee the same object. Without the scope each would get its own copy and the selection would never reach the UI.ProfileViewModelcould not inject an@ActivityScopedclass or theActivity; that is a build error, because the ViewModel outlives the Activity instance.
Run the idea in plain Kotlin
A tiny model of the tree: each component caches its own scoped objects and asks its parent for anything it does not own. Rotation throws away the Activity component but keeps the retained one.
// Each component caches its own scoped objects for as long as it lives
class Component(val name: String, val parent: Component?) {
private val scoped = mutableMapOf<String, Any>()
fun <T : Any> scoped(key: String, create: () -> T): T {
@Suppress("UNCHECKED_CAST")
return scoped.getOrPut(key) {
println(" create " + key + " in " + name)
create()
} as T
}
}
class Repo // @Singleton
class LiveUpdates // @ActivityRetainedScoped
class Formatter // unscoped
class Screen(val repo: Repo, val live: LiveUpdates, val formatter: Formatter)
// What Hilt generates for an Activity: scoped bindings come from the owning component
fun injectActivity(app: Component, retained: Component) = Screen(
repo = app.scoped("Repo") { Repo() },
live = retained.scoped("LiveUpdates") { LiveUpdates() },
formatter = Formatter(),
)
fun main() {
val app = Component("SingletonComponent", null)
var retained = Component("ActivityRetainedComponent", app)
println("Open screen:")
val first = injectActivity(app, retained)
println("Rotate (new Activity, same retained component):")
val rotated = injectActivity(app, retained)
println(" repo same: " + (first.repo === rotated.repo) +
", live same: " + (first.live === rotated.live) +
", formatter same: " + (first.formatter === rotated.formatter))
println("Finish and reopen (new retained component):")
retained = Component("ActivityRetainedComponent", app)
val reopened = injectActivity(app, retained)
println(" repo same: " + (first.repo === reopened.repo) +
", live same: " + (first.live === reopened.live))
}Expected output:
Open screen:
create Repo in SingletonComponent
create LiveUpdates in ActivityRetainedComponent
Rotate (new Activity, same retained component):
repo same: true, live same: true, formatter same: false
Finish and reopen (new retained component):
create LiveUpdates in ActivityRetainedComponent
repo same: true, live same: false
In production
- Low-RAM devices showed growing memory and occasional OOM crashes after long sessions; LeakCanary in a debug build reported
MainActivityinstances retained byScreenTracker. ScreenTrackerwas@Singleton. Each Activity calledtracker.register(this)inonCreate()so the tracker could read the current screen name, and nothing ever unregistered.- Every rotation added another destroyed Activity to the singleton's list, so none of them could be garbage-collected.
- They reproduced it by rotating the screen twenty times and reading the LeakCanary trace.
ScreenTrackerstopped storing Activities. The per-screen part became@ActivityScoped class ScreenReporter @Inject constructor(activity: Activity, tracker: ScreenTracker), which reads what it needs from the Activity and passes only plain data (the screen name) to the singleton.- They added LeakCanary's instrumentation test rule (
DetectLeaksAfterTestSuccess) to the UI tests that rotate screens, so a new leak fails CI.
- After logging out and logging in as another account, the settings screen still showed the old account's name and email.
ProfileRepositorywas@Singletonand stored theuserIdand the loaded profile in fields the first time it was used. Logout cleared the token but never touched the repository.- QA had missed it because they always tested with one account.
- They reproduced it by logging in as user A, opening settings, logging out, logging in as user B and reopening settings.
ProfileRepositorystayed@Singleton(several screens share it), but stopped storing theuserId: it now reads the current user from theSessionRepositoryflow on every call and keys its cache by user id.- The logout use case now calls
clear()on every repository that caches user data. - A plain unit test with a fake
SessionRepositoryswitches users and asserts the second profile comes back.
Common mistakes
- Scoping everything to @Singleton. Every object lives for the process, costs a lock on first access, and shares its state with every screen and user session. Leave cheap, stateless objects unscoped and scope to the narrowest component that matches the object's real lifetime.
- Thinking a module's component scopes its bindings.
@InstallIn(SingletonComponent::class)without@Singletonon the@Providesmethod still gives a new instance per request. - Forgetting @InstallIn on a @Module. Hilt reports a build error saying the module is missing
@InstallIn. Add it with the component whose lifetime fits. - Injecting Activity-scoped things into a ViewModel.
ViewModelComponentis not a child ofActivityComponent, so the build fails. Pass what the ViewModel needs as data, or move the object to@ActivityRetainedScopedif it holds no Activity reference. - Storing per-user state in a @Singleton without clearing it. The object survives logout. Key caches by user and clear them on logout, or read the current user each time.
- Expecting @ActivityRetainedScoped or @Singleton to survive process death. Both are in memory. State that must survive process death belongs in
SavedStateHandle, DataStore or Room.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“Explain the Hilt component hierarchy and what each scope means.”
“What does scoping cost, and when is it worth it?”
“A developer put @Singleton on a class that holds a reference to a ViewModel or Activity. What goes wrong and how do you fix it?”
“How do you test a class whose dependencies come from Hilt?”
Quiz
Which component is the direct parent of ViewModelComponent?
What happens if you annotate a class with @Singleton and it stores a reference to an Activity?
A @HiltViewModel's constructor takes a class annotated @ActivityScoped. What happens?
A class has no scope annotation. What does Hilt do?
0 of 4 answered
Mini task
Exercise: Scope audit and fix (15 min)
- Open a Hilt project (or create a minimal one with
@HiltAndroidApp, one@AndroidEntryPointActivity and two@HiltViewModelclasses). - Add
class SelectionState @Inject constructor()with aninitblock that logs"SelectionState created". Inject it into both ViewModels and into aclass SelectItem @Inject constructor(state: SelectionState)that the first ViewModel also injects. - Run the app with no scope annotation. Count the log lines: one per injection.
- Annotate
SelectionStatewith@ViewModelScoped. Rerun: the first ViewModel and itsSelectItemnow share one instance, and the second ViewModel has its own. - Change it to
@Singleton. Rerun: one instance for the whole process. Rotate and confirm nothing new is created. - Change it to
@ActivityScopedand build. Read the error: a ViewModel cannot seeActivityComponentbindings. - Done condition: you can state, for each of the four runs, how many instances exist and why, and the build error from step 6 names the scope mismatch.