Using Hilt in the network module

Priyansh Kedia
CodeX
Published in
3 min readJul 9, 2021

--

Google released Dagger which in contrast to other dependency injection frameworks provides strictly generated implementation (no reflection) meaning that it can be easily used in Android applications.

Dependency injection with a framework like Dagger help in reducing boilerplate code to a great extent and helps developers speed up the development process. Dependency injection (DI) allows you to make the code very modular, and thus makes it more efficient to be unit-tested.

Photo by IGOR FIGUEREDO on Unsplash

Hilt provides a standard way to incorporate Dagger dependency injection into an Android application. Hilt tries to simplify Dagger-related infrastructure for Android apps and provides an easy way to provision different bindings to various build types (e.g. testing, debug, or release).

In this blog series, we will understand how Hilt can be used to create a network module, to avoid writing duplicate code for networking in Android.

Note that this series contains code written in Kotlin.

Understanding the structure of our network module

We start by adding the dependencies for Hilt in android. All these dependencies can be found here.

We then create the application class. Android's application class is the base class within an app that contains all other components. The Application class is instantiated before any other class in the android lifecycle.

@HiltAndroidApp
class MyApp: Application() {
override fun onCreate() {
super.onCreate()
instance = this
}

companion object {
lateinit var instance: MyApp
private set
}
}

In the above code, we create a class and extend it to the Application class. Then a private instance of our class is created and instantiated inside onCreate.

A public static (companion object in Kotlin) is then created to access the instance of the application.

This is what the directory structure of our module looks like

The directory structure of our network module

We will understand the contents of each of these files thoroughly.

ApplicationModule

@Module
@InstallIn(ApplicationComponent::class)
class ApplicationModule {

@Provides
@Singleton
fun provideApp(): Application {
return MyApp.instance
}
}

@Module is used to annotate the class that contributes to the object graph in DI.

@InstallIn specifies which class the module will be installed in. We use ApplicationComponent to install the module throughout the lifecycle of the application.

@Provides annotates the method to create a provider method binding.

@Singleton is used to specify that only a single instance of the class is created throughout.

We can see that this method will be used to provide instances of the application class that we instantiated in the application class. This method will not be used in the networking module directly.

Next, we will understand the NetworkModule. Read about it here.

--

--