Using Hilt to manage dependencies
In this section, we will discuss the Hilt DI library, how we can use it in an Android application, and the extra features it provides on top of the Dagger 2 library.
Hilt is a library built on top of Dagger 2 with a specific focus on Android applications. This is to remove the extra boilerplate code that was required to use Dagger 2 in an application. Hilt removes the need to use @Component
and @Subcomponent
annotated classes and in turn offers new annotations:
- When injecting dependencies in Android classes, we can use
@HiltAndroidApp
forApplication
classes,@AndroidEntryPoint
for activities, fragments, services, broadcast receivers, and views, and@HiltViewModel
forViewModels
. - When using the
@Module
annotation, we now have the option to use@InstallIn
and specify an@DefineComponent
annotated class, which represents the component the module will be added to. Hilt provides a set of useful components to install modules in:@SingletonComponent...