Android & Jetpack Compose (50 Qs)•Part 2: Compose Internals, Persistence, DI & Background Work (11 - 24)
What is Dependency Injection with Hilt and what are the standard Component Scopes?
senior LevelMost AskedCode ExampleDependency InjectionComponentsDocker & Containers
In Simple Words: Hilt is Google's recommended dependency injection library for Android, built on top of Dagger:
- Eliminates manual boilerplate by generating Dagger components for Android lifecycles:
@Singleton(SingletonComponent): Lives for the entire application lifetime.@ActivityRetainedScoped(ActivityRetainedComponent): Survives configuration changes (shared across ViewModels).@ViewModelScoped(ViewModelComponent): Injected into ViewModels; cleared with the ViewModel.@ActivityScoped(ActivityComponent): Lives for the lifecycle of a single Activity.
kotlin
@HiltViewModel
class OrderViewModel @Inject constructor(
private val orderRepository: OrderRepository
) : ViewModel() { ... }