In Hilt, which scope fits an article cache shared by the ViewModels of one reader activity that must survive rotation, and why not @ActivityScoped or @Singleton?
answer
- component lifetimes bound scoped objects
- rotation destroys the activity component
- a retained component sits above it
- process-wide is too long
- unscoped is the default
basics
~20 s@ActivityRetainedScoped: ActivityRetainedComponent survives configuration changes and ends when the activity finishes, and ViewModels can see it. @ActivityScoped is rebuilt on every rotation, losing the cache; @Singleton keeps it for the whole process and shares it across every reader screen.
solid answer
~40 sA Hilt scope ties an instance to one component instance, so the choice is really which component's lifetime matches the object's. `ActivityComponent`, with `@ActivityScoped`, is created in `onCreate()` and destroyed in `onDestroy()`, so a rotation throws the cache away; it is also invisible to ViewModels. `ActivityRetainedComponent`, with `@ActivityRetainedScoped`, is created at the first `onCreate()` and destroyed at the last `onDestroy()`, survives rotation, and is the parent of `ViewModelComponent`, so every ViewModel of that activity shares the instance. `@Singleton` would work mechanically but outlives the screen: one cache for every reader activity, held until the process dies. If only one ViewModel used it, `@ViewModelScoped` would be tighter still. Remember that bindings are unscoped by default, and that Dagger's guidance is to scope for correctness rather than by habit.
code
kotlin · 21 lines@ActivityRetainedScoped
class ReaderArticleCache @Inject constructor() {
private val bodies = mutableMapOf<String, String>()
fun get(id: String): String? = bodies[id]
fun put(id: String, body: String) { bodies[id] = body }
}
@HiltViewModel
class ArticleBodyViewModel @Inject constructor(
private val cache: ReaderArticleCache
) : ViewModel()
@HiltViewModel
class RelatedArticlesViewModel @Inject constructor(
private val cache: ReaderArticleCache
) : ViewModel()
@Singleton
class BookmarkStore @Inject constructor(
@ApplicationContext private val context: Context
)go deeper
Recall that Hilt bindings are unscoped by default and that each scope annotation belongs to one predefined component.
Explain each component's lifetime and parent, and why ViewModels can see retained-scoped bindings but not activity-scoped ones.
Pick the narrowest scope that is still correct across rotation, and audit long-lived scoped classes for references that outlive their owner.
Set a policy that scoping needs a correctness reason, and weigh how a single-activity architecture changes what retained scope means for memory.
## A scope is a component lifetime In Hilt, a **scope annotation** says: create this binding once per instance of a particular component, and hand every request from that component and its children the same object. Hilt's predefined components each follow an Android lifecycle, so choosing a scope means choosing **how long the object lives and who shares it**. | Component | Scope | Created at | Destroyed at | |---|---|---|---| | `SingletonComponent` | `@Singleton` | `Application#onCreate()` | process death | | `ActivityRetainedComponent` | `@ActivityRetainedScoped` | first `Activity#onCreate()` | last `Activity#onDestroy()` | | `ViewModelComponent` | `@ViewModelScoped` | ViewModel created | ViewModel destroyed | | `ActivityComponent` | `@ActivityScoped` | `Activity#onCreate()` | `Activity#onDestroy()` | | `FragmentComponent` | `@FragmentScoped` | `Fragment#onAttach()` | `Fragment#onDestroy()` | | `ViewComponent` | `@ViewScoped` | view constructed | view destroyed | | `ServiceComponent` | `@ServiceScoped` | `Service#onCreate()` | `Service#onDestroy()` | The hierarchy matters as much as the lifetimes: `ActivityRetainedComponent` is a child of `SingletonComponent`, and both `ViewModelComponent` and `ActivityComponent` are children of `ActivityRetainedComponent`. `FragmentComponent` sits under `ActivityComponent`. ## Working through the article cache The requirement has three parts: shared by **all ViewModels of one reader activity**, **survives rotation**, and should not outlive that reading session. 1. **`@ActivityScoped`** fails twice. A rotation destroys the activity and its `ActivityComponent`, so the cache is rebuilt empty. And ViewModels are injected from `ViewModelComponent`, which is not below `ActivityComponent`, so a ViewModel cannot even inject it. 2. **`@Singleton`** compiles and survives rotation, but it is one cache for the entire process: two reader activities on the back stack share it, and it stays in memory after the reader closes. 3. **`@ActivityRetainedScoped`** matches: one instance per logical activity, kept across configuration changes, released when the activity finishes, and visible to every ViewModel because `ViewModelComponent` is its child. 4. If only **one** ViewModel needs it, **`@ViewModelScoped`** is narrower and therefore better. In a single-activity app, `@ActivityRetainedScoped` lives as long as the whole UI, which makes it nearly app-wide. State that belongs to one destination then belongs in that destination's ViewModel or a `@ViewModelScoped` binding. ## Misconceptions the documentation calls out - **Bindings are unscoped by default.** Each request gets a new instance unless a scope is present. - **Installing a module does not scope it.** Only bindings that carry a scope annotation are scoped, and a binding's scope must match the component its module is installed in. - **A fragment scope is per fragment instance**, not shared by all fragments; each fragment gets its own `FragmentComponent`. - **Scoping costs** generated code and runtime work, and keeps the object in memory until the component dies. Dagger's guidance is to scope only when correctness requires a shared instance, and to measure before scoping for performance, where Dagger's `@Reusable` may fit better. ## Reading a scope bug from its symptoms Scope mistakes rarely announce themselves as scope mistakes. They surface as behaviour, and each symptom points at a likely cause: - **State vanishes on rotation**: the holder is `@ActivityScoped`, `@FragmentScoped` or unscoped where a retained or ViewModel scope was needed. - **Two screens see each other's data**: the holder is `@Singleton`, or `@ActivityRetainedScoped` in a single-activity app, where a narrower scope was intended. - **Two instances where one was expected**: the binding is unscoped, often a `@Binds` with no scope pointing at an unscoped implementation. - **A build error naming a missing binding for an activity type**: a long-lived class asked for something only an activity can provide. - **Memory that grows each time a screen opens**: a scoped object is collecting references, such as listeners, that belong to shorter-lived objects. The first question in each case is the same: which component holds this binding, and how long does that component live? ## When a scope outlives its owner Hilt's graph prevents the most direct leak at compile time. A `@Singleton` or `@ActivityRetainedScoped` class whose constructor asks for an `Activity` or an `@ActivityContext Context` does not compile, because those bindings exist only in `ActivityComponent` and below, and a parent never sees a child's bindings. The fix is usually `@ApplicationContext`, or moving the work that needs an activity into the UI layer. The graph cannot stop **runtime** leaks. A long-lived scoped object that stores something handed to it later, such as a listener lambda capturing the activity or a view passed into a method, keeps that activity alive after `onDestroy()`. The same applies to passing an activity through an assisted ViewModel factory, which Hilt's documentation explicitly warns against. A useful review question for every scoped class is: what does it hold, and does every held object live at least as long as the component?
- A @Singleton class asks for an @ActivityContext Context; when does it fail?At compile time. `@ActivityContext Context` is bound only in `ActivityComponent` and its children, and `SingletonComponent` cannot see child bindings, so Dagger reports a missing binding. Switching to `@ApplicationContext` fixes it when the class only needs resources or system services.
- Is a @FragmentScoped binding shared by two fragments in the same activity?No. Each fragment instance gets its own `FragmentComponent`, so each gets its own scoped instance. To share across fragments of one activity, scope higher: `@ActivityScoped` if it may die on rotation, `@ActivityRetainedScoped` if it must survive.
- Why not scope every repository @Singleton just to be safe?A scope keeps the object in memory for the component's lifetime and adds generated code and runtime work. Scope a binding when sharing one instance is required for correctness, such as holding shared state or synchronising access; otherwise unscoped bindings are cheaper and harder to misuse.
- Bindings in Hilt are singletons unless you say otherwise.
- An @ActivityScoped object survives a screen rotation.
- All fragments of one activity share a @FragmentScoped instance.
- Installing a module in a component scopes all of its bindings.
- A @Singleton can safely take an @ActivityContext Context if you null it later.
- Scoping everything @Singleton is free and avoids bugs.