Hilt Basics Flashcards
ARCHITECTURE › Dependency Injection
- What problem does dependency injection (and Hilt) solve?
- It supplies a class's dependencies from outside instead of the class constructing them, which decouples code, improves testability (easy to swap mocks), and centralizes object-graph management. Hilt automates this on Android with compile-time wiring.
- What does @HiltAndroidApp do and where does it go?
- It goes on your Application subclass and is mandatory. It triggers Hilt's code generation and creates the application-level (SingletonComponent) container that is the parent of all other Hilt components.
- What is @AndroidEntryPoint for, and which classes support it?
- It enables Hilt field injection into Android framework classes: Activity, Fragment, View, Service, and BroadcastReceiver (the Application uses @HiltAndroidApp; ViewModel uses @HiltViewModel). Injected fields must not be private.
- When can you use @Inject constructor injection, and what does it tell Hilt?
- When you own the class and can annotate its constructor. It tells Hilt how to create the type and what its dependencies (constructor params) are, so Hilt can wire it automatically without a module.
- @Provides vs @Binds: when do you use each?
- Both live in a @Module. @Binds is an abstract function that maps an interface to an @Inject-annotated implementation you own (no body, less generated code). @Provides is a concrete function whose body builds the instance, used for interfaces you can't constructor-inject, third-party types, or builder-pattern construction.
- How do you provide two different bindings of the same type with Hilt?
- Define custom @Qualifier annotations and apply them to each @Provides/@Binds and to the injection point. Hilt uses the qualifier to disambiguate. Built-in qualifiers include @ApplicationContext and @ActivityContext for Context.
- How do you inject a ViewModel with Hilt, including in Compose?
- Annotate the ViewModel with @HiltViewModel and use @Inject constructor. Retrieve it via by viewModels() in an @AndroidEntryPoint Activity/Fragment, or hiltViewModel() inside a composable. SavedStateHandle is provided automatically.
- What does Hilt generate under the hood?
- Hilt is built on Dagger. At build time it generates Dagger components for the standard Android classes, wires and validates the dependency graph (failing compilation on missing deps or cycles), and emits the code that creates objects and performs injection.
- What is @ViewModelScoped vs @Singleton vs unscoped in Hilt?
- Unscoped (default) gives a new instance per request. @ViewModelScoped ties one instance to a single ViewModel (ViewModelComponent lifetime). @Singleton ties one instance to the SingletonComponent (app lifetime). Each scope binds an instance to its component's lifecycle.