Hilt scopes and components

Learn Hilt scopes and components in Android to master dependency lifecycles, prevent memory leaks, and avoid the costs of improper scoping. About 25 minutes.

Why it matters

  • Choosing the wrong scope causes memory leaks (a @Singleton holding 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 @ActivityScoped class 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:

ComponentScope annotationParentLives from / to
SingletonComponent@Singletonnone (root)Application#onCreate() until the process dies
ActivityRetainedComponent@ActivityRetainedScopedSingletonComponentFirst Activity#onCreate() to the final onDestroy(); survives configuration changes
ViewModelComponent@ViewModelScopedActivityRetainedComponentViewModel created to ViewModel cleared
ActivityComponent@ActivityScopedActivityRetainedComponentActivity#onCreate() to onDestroy(); recreated on rotation
FragmentComponent@FragmentScopedActivityComponentFragment#onAttach() to onDestroy()
ViewComponent@ViewScopedActivityComponentView created to destroyed
ViewWithFragmentComponent@ViewScopedFragmentComponentView created to destroyed (Views with @WithFragmentBindings)
ServiceComponent@ServiceScopedSingletonComponentService#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.

Hilt components and how long they live
Hilt components and how long they live SingletonComponent lives for the whole process; below it ActivityRetainedComponent survives rotation and is the parent of ViewModelComponent, one per ViewModel, and ActivityComponent, one per Activity, which in turn is the parent of FragmentComponent and ViewComponent. SingletonComponent the whole process ActivityRetainedComponent survives rotation ViewModelComponent one ViewModel ActivityComponent one Activity FragmentComponent one Fragment ViewComponent one View
Lifetimes get shorter down the tree. A component can use bindings from the components above it, never from below.

Notes

  • Hierarchy: SingletonComponent → ActivityRetainedComponent → (ViewModelComponent, ActivityComponent → (FragmentComponent → ViewWithFragmentComponent, ViewComponent)); ServiceComponent sits directly under SingletonComponent.
  • A child can use parent bindings, never the reverse. A ViewModel can use @Singleton and @ActivityRetainedScoped bindings, but not @ActivityScoped ones or the Activity itself.
  • @Singleton means one instance per SingletonComponent, which is one per process. Unlike a Kotlin object, 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 @Inject constructor or the scope is on its @Provides / @Binds method.
  • Installing a module in SingletonComponent does not make its bindings singletons; only @Singleton does.
  • @ActivityRetainedScoped survives configuration changes and is released when the Activity finishes. It does not survive process death; nothing in memory does.
  • @ViewModelScoped shares 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.addOnClearedListener or ViewModelLifecycle.addOnClearedListener. Hilt does not call close() on scoped objects for you.
  • Testing: @TestInstallIn replaces a module for the whole test source set, @UninstallModules plus a nested @InstallIn module replaces it for one class, and @BindValue binds 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, UserApi and UserRepository are @Singleton because they are expensive or hold a cache that every screen should share. The repository's clear() exists because a process-wide cache outlives a user session.
  • LiveUpdates is @ActivityRetainedScoped: rotation does not reconnect the socket, and addOnClearedListener closes it when the Activity finishes. The ViewModel can inject it because ViewModelComponent is a child of ActivityRetainedComponent.
  • SelectionState is @ViewModelScoped, so SelectItem and ProfileViewModel see the same object. Without the scope each would get its own copy and the selection would never reach the UI.
  • ProfileViewModel could not inject an @ActivityScoped class or the Activity; 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

Singleton screen tracker leaking every Activity
  • Low-RAM devices showed growing memory and occasional OOM crashes after long sessions; LeakCanary in a debug build reported MainActivity instances retained by ScreenTracker.
  • ScreenTracker was @Singleton. Each Activity called tracker.register(this) in onCreate() 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.
The fix
  • They reproduced it by rotating the screen twenty times and reading the LeakCanary trace.
  • ScreenTracker stopped 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.
Previous user's profile after switching accounts
  • After logging out and logging in as another account, the settings screen still showed the old account's name and email.
  • ProfileRepository was @Singleton and stored the userId and 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.
The fix
  • They reproduced it by logging in as user A, opening settings, logging out, logging in as user B and reopening settings.
  • ProfileRepository stayed @Singleton (several screens share it), but stopped storing the userId: it now reads the current user from the SessionRepository flow 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 SessionRepository switches 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 @Singleton on the @Provides method 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. ViewModelComponent is not a child of ActivityComponent, so the build fails. Pass what the ViewModel needs as data, or move the object to @ActivityRetainedScoped if 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)

  1. Open a Hilt project (or create a minimal one with @HiltAndroidApp, one @AndroidEntryPoint Activity and two @HiltViewModel classes).
  2. Add class SelectionState @Inject constructor() with an init block that logs "SelectionState created". Inject it into both ViewModels and into a class SelectItem @Inject constructor(state: SelectionState) that the first ViewModel also injects.
  3. Run the app with no scope annotation. Count the log lines: one per injection.
  4. Annotate SelectionState with @ViewModelScoped. Rerun: the first ViewModel and its SelectItem now share one instance, and the second ViewModel has its own.
  5. Change it to @Singleton. Rerun: one instance for the whole process. Rotate and confirm nothing new is created.
  6. Change it to @ActivityScoped and build. Read the error: a ViewModel cannot see ActivityComponent bindings.
  7. 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.
Next: Koin as an alternative