Skip to content
Related Articles

Related Articles

Improve Article

How Does the Dagger Work in Android?

  • Last Updated : 09 May, 2021

When we create a new Android Project, eventually we start accumulating different-different dependencies to get certain functionalities, but over time managing them becomes cumbersome, thus an injection framework like Dagger comes into play. However, setting up an injection service like Dagger requires much amount of boilerplate code and has a very steep learning curve. Originally adding raw dependency/version of Dagger without Android Support is a nightmare.

BUT….. 

Then comes Dagger-Android, which changes this game and satisfies everything which raw Dagger lacked, like reduced pre-made (boiler-plate) code, still it wasn’t successful. Recently Dagger-Hilt was released in the part of the highly famous Jetpack libraries, and now Google also recommends a certain way to achieve the implementation. The following are ups of using Dagger-Hilt as mentioned by them:

  1. Provides a different set of bindings for different build types and flavors.
  2. Make the raw dagger code easy and readable for developers.
  3. Takes care of where to inject dependencies
  4. All of the code remaining generations which occur are handled by the dagger itself by using annotations and thus removing all the boilerplate code.

But still, the question remains…

How Does Dagger Work?

For that, let’s go through this quick story:



Let me Introduce: Spandan an Android developer, and his newly developed robot Zen

Spandan may be a mysterious guy but maybe an excessive amount of solitary one…

Now Zen has two main features:

  • answer “Like a Daisy” when asked “How are you doing?
  • walk around Spandan’s apartment avoiding obstacles.

To develop Zen, Spandan didn’t use dependency injection.

Result: Zen is quickly functional and executes its functionalities very easily (walking and speaking).

One day, Spandan wants to vary Zen’s behavior because well… having a robot that walks around the home is nice but now he doesn’t do much right?

For this reason, our developer must forget his motto “the less I bother, the better”. Indeed, whether it’s to vary Zen’s behavior or test his code, he must touch his code. If its code is sufficiently modular, this could help it considerably. But to switch Zen’s behavior only during the tests the matter isn’t solved.

Luckily, Spandan finally discovered dependency injection! A revelation for him! Yes, it takes longer to line up, but once done, no more headache! Indeed, Spandan divided his robot into several distinct and independent parts (or modules): the top, the proper arm, the left arm, etc. These will all be added to Zen’s body, which, on the opposite hand, needs these parts to function.



Zen’s new dependencies (all in different parts)

These different parts on which Zen depends are called dependencies. These are created independently of his body, they are going to be “injected” into his code. that’s to mention, they’re simply “connected” to Zen’s body, which can use them to steer and talk. This implies that, if, for instance, Spandan wants Zen to require advantage of his ride to wash up, he only has got to modify the corresponding dependency (here, one among the arms). additionally, when Spandan wants to perform different function tests on Buggy, he will define dependencies especially for this case, and alter the robot’s behavior in order that it remains motionless during the “walk” functionality test.

Understanding Dagger

Before starting with Dagger-Hilt we’d like to know Dagger basics. during this section, you’ll understand the Dagger and its terminologies. Basically, to know Dagger we’ve to know the 4 major annotations,

  1. Module
  2. Component
  3. Provides
  4. Inject

To understand it better during a basic course, think module as a provider of dependency and consider an activity or the other class as a consumer. Now to supply dependency from provider to consumer we have a bridge between them, in Dagger, Component work as that specific bridge.

Now, a module may be a class, and that we annotate it with @Module for Dagger to know it as Module. A component is an interface, which is annotated with @Component and takes modules in it. (But now, this annotation isn’t required in Dagger-Hilt). Inject is an annotation that’s wont to define a dependency inside the buyer.

Understanding Dagger through FlowChart

#1. Setting up a fresh Project

Create a Project

  1. Select Empty Activity then Next
  2. Name: GeeksforGeeksDaggerTutorial
  3. Package name: com.geeksforgeeks.dagger
  4. Language: Kotlin
  5. Finish

Your starting project is prepared now

#2. Add dependencies

Add the subsequent dependencies within the app’s build.gradle file:

implementation “androidx.recyclerview:recyclerview:{latest-version}”

implementation ‘android.arch.lifecycle:extensions:{latest-version}’

implementation ‘com.github.bumptech.glide:glide:{latest-version}’

implementation ‘androidx.activity:activity-ktx:{latest-version}’

Your Initial Gradle File is now ready!

#3. We need the enum to represent the UI State. We will create that in the utils package.

Kotlin




package com.geeksforgeeks.dagger.utils
  
enum class Status {
    SUCCESS,
    ERROR,
    LOADING
}

Now we need a utility class that will handle the communication of the current state of Network Call to the User Interface (UI) Layer. We are (for this project) naming it as Resource.

#4. Create a Kotlin class ‘Resource.kt’ inside the same utils package and add the following code:

Kotlin




package com.geeksforgeeks.dagger.utils
  
data class Resource<out T>(val status: Status, val data: T?, val message: String?) {
  
    companion object {
  
        fun <T> success(data: T?): Resource<T> {
            return Resource(Status.SUCCESS, data, null)
        }
  
        fun <T> error(msg: String, data: T?): Resource<T> {
            return Resource(Status.ERROR, data, msg)
        }
  
        fun <T> loading(data: T?): Resource<T> {
            return Resource(Status.LOADING, data, null)
        }
    }
}

We are now ready to roll with this package! Hope you got the true aroma through this article and would’ve well understood how does dagger work 🙂

Want a more fast-paced & competitive environment to learn the fundamentals of Android?
Click here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!



My Personal Notes arrow_drop_up
Recommended Articles
Page :