Starting with HILT

tanya anand
2 min readFeb 13, 2021

--

HILT made Dependency Injection Easy.

Let's see How...

Integrating Dagger-Hilt

Add This to your build.gradle(:app)

Add this to your build.gradle(project)

Yup! we are all set.

Don't forget to click “sync now”

Step 1

Create MyApplication that extends Application.

We need to annotate with @HiltAndroidApp.

Hilt needs to know where our application class is, so that it can generate various other dependent classes.

Must add this to android manifest as:

android:name=".MyApplication"

Step 2

Create class AppModule.kt. which acts as a container for all the dependencies that stay for a specific amount of time.

Let me try to explain it one by one.

@Module tells Hilt, this is the place where you can find all dependency providers.

@InstallIn tells hilt how longer we need these dependency providers.

SingletonComponent tells that, this dependency provider will remain alive till the app is alive. we also have different components as ActivityComponent, ActivityRetainedComponent, etc. which has different life period.

@Singleton tells hilt, not to create new instance everytime, instead supply the same instance everywhere needed.

@Named is used to differentiate between the return type.

i.e. in the above example, the return type of both function are same. This will confuse Hilt, on which one to bind. To avoid this we give a name to return type.

Step 3:

Create ViewModel

@HiltViewModel: The ViewModel annotated with HiltViewModel will be available for creation and can be retrieved by default in an Activity or Fragment annotated with AndroidEntryPoint.

it has a dependency RandomStr2 whose return type is String, or distinguished with @Named annotation, This will be injected by Hilt.

Step 4:

Now its time for our MainActivity

@AndroidEntryPoint tells Hilt, this is file where we have to inject dependencies.

@Inject
@Named("Str1")
lateinit var randomString1 : String

@Inject tells Hilt to initialize this variable by dependency injection.

@Named is used to differentiate between the return type, which helps dagger to identify dependency provider.

private val viewModel : MyViewModel by viewModels()

This will create an instance of MyViewModel and store it in ViewModel. This creation is done by lazy instantiation. Thus to call init {} inside MyViewModel.kt we have to call viewModel once.

We are all set to go!

Hope this helps you.

--

--

tanya anand
tanya anand

No responses yet