Hilt Scopes & Components Flashcards

ARCHITECTURE › Dependency Injection

What does it mean that a Hilt binding is unscoped, and what is the default?
Unscoped is the default: Hilt creates a brand-new instance every time the binding is requested. No instance is cached or reused.
Match the scope annotations to their Hilt components.
@Singleton -> SingletonComponent, @ActivityRetainedScoped -> ActivityRetainedComponent, @ViewModelScoped -> ViewModelComponent, @ActivityScoped -> ActivityComponent, @FragmentScoped -> FragmentComponent, @ViewScoped -> View/ViewWithFragmentComponent, @ServiceScoped -> ServiceComponent.
How does ActivityRetainedComponent differ from ActivityComponent in lifetime?
ActivityRetainedComponent survives configuration changes (created at the first onCreate, destroyed at the last onDestroy). ActivityComponent is recreated on every config change, tied to a single Activity instance's onCreate/onDestroy.
What exactly does @ViewModelScoped guarantee?
A single instance of the scoped type is shared across all dependencies injected into one ViewModel. A different ViewModel instance receives its own separate instance.
You need one instance of a class shared across several different ViewModels. Which scope?
@ActivityRetainedScoped (or @Singleton). @ViewModelScoped would give each ViewModel its own copy, not a shared one.
Why is scoping a dependency that holds an Activity Context to @Singleton dangerous?
The Singleton lives for the whole app, so it keeps the Activity Context alive past the Activity's destruction, leaking the Activity and its view tree. Use an application Context or a narrower scope.
When does the SingletonComponent get created and destroyed?
Created at Application#onCreate() and destroyed when the Application is destroyed; its scoped bindings live for the entire app process.
In Jetpack Compose, how do you obtain a Hilt ViewModel and what is it scoped to?
Call hiltViewModel(); it returns a @HiltViewModel-annotated ViewModel scoped to the current navigation destination (NavBackStackEntry), provided by ViewModelComponent.
What does scoping a binding to a component imply about which other bindings can use it?
A binding installed in a component is available to that component and any child component below it in the hierarchy, but not to parent or sibling components.

Back to Hilt Scopes & Components