Skip to content

Hilt ‐ About Hilt

Devrath edited this page Feb 4, 2024 · 11 revisions

Hilt Basics

Application Class

  • Application class is mandatory for hilt, Based on the application class the application-wide singleton is created.
  • We use the annotation @HiltAndroidApp annotated to the application class.

AndroidEntryPoint

  • The @AndroidEntryPoint indicates that the dependencies will be provided by Hilt to your component.
  • There can be more than one entry point.
  • For each entry point hilt tries to generate individual components. By doing so it tries to get rid of the dagger component that was needed earlier. As a result, developers don't have to write them making it easier for the developers.
  • If we annotate the fragment, we need to annotate the host activity as well.

Dagger compared with hilt

  • Hilt is built on top of Dagger.
  • Hilt simplifies dagger-related infrastructure for Android applications.
  • Because Android OS instantiates many of its own framework classes, using a dagger in an Android app requires you to write a substantial amount of boilerplate code.
  • Hilt reduces the substantial amount of boilerplate code by automatically generating the components annotations and qualifiers
  • Hilt provides scope annotations out-of-the-box.
  • Hilt also provides pre-defined bindings for Activity and Application.
  • Hilt provides predefined qualifiers to represent @ApplicationContext and @ActivityContext.

Hilt currently supports the following Android classes

Hilt Supports
Application
Activity
Fragment
View-Model
View
Service
BroadcasrReciever
Compose
Navigation
WorkManager

Component lifetimes and scopes

Android class Generated Component Scope Created At Destroyed At Injected For
Application SingletonComponent @Singleton Application#onCreate() Application destroyed Application
Activity ActivityCompoment @ActivityScoped Activity#onCreate() Activity#onDestroyed() Activity
ViewModel ViewModelComponent @ViewModelScoped ViewModel created ViewModel destroyed ViewModel
Fragment FragmentComponent @FragmentScoped Fragment#onAttach() Fragment#onDestroy() Fragment
View ViewCompoenet @ViewScoped View#super() View destroyed View
Service ServiceComponent @ServiceScoped Service#onCreate() Service#onDestroy() Service

Component Hierarchy

hilt-hierarchy

Clone this wiki locally