Ideas are easy. Implementation is hard. Be Passionate.

Dagger2 dependency injection in MVP android

Dagger 2 is awesome dependency injection library which is used in android. In this tutorial, we will try to understand what is Dagger2 and why is required dependency injection and how to use in building the architectural based android app? Even Dagger2 is much comfortable with using RxJava Observable. Sounds crazy 🙂 Let’s see first of all what is Dagger 2?

What is Dagger 2?

Dagger 2 is awesome java library which provides the alternative way of Object instantiation. You do not worry about the constructor with a different type of argument. Dagger 2 will take care automatically based on the qualifier. What you need to do just used annotated @Inject then all required object will be created and assigned automatically.

Why is required dependency injection and what are the benefits to using this?

While building any android app we are instantiating at least 40 objects or more in any of the android project. But later if those are required to refactor, change argument type and change in the number of arguments, it will create many problems in many places in existing code. But Dragger 2 will handle this type of problem very smartly.

Using dagger 2 having a lot of benefits, for example, Maintainability, testability, low coupling, easy singletons, less boilerplate code and order of object instantiation etc.

I will describe its benefits into deep to explaining with awesome features of Dagger2. But to understand the core features of Dagger2 we need to look at the architectural diagram. Here is detail:

Application Components are application specific objects like Network communication, Sqlite Database component and SharedPrefernce etc that are injected into activity. Its means object reference scope is available for application context.

Activity Components can have activity specific objects like Toolbars, Shared UI, or any custom based components want to inject into Fragments, Views, etc. It means object reference scope available for Activity context. It avoids memory leak kind of issue.

Dagger 2 is annotation based java library. Ok great, Let’s see what are fields available in Dagger2.

@Scope – It means any particular object availability indoors scope. Dagger 2 has a more concrete way to do scoping through custom annotations. It can be @PerApplication @PerActivity, @PerFragment etc. By default, it provides only @singletone scope for root component.

@Singletone – It means that if any object is already created then do not need to recreate it, we can reuse this object throughout the application. For example, SharedPreference which we can reuse object throughout the application anywhere.

@Module -A module is the part of the application that provides some functionality as a dependency for injecting.

@Component – It is an interface and also part of an application to consume some functionality. It enabled for selected modules to perform as a dependency.

@Provide – This annotation is used inside the module it means it will tell to Dagger to instantiating the object for dependency.

@Inject – It can be used on a constructor, field or a method. Dagger will inject the object for a class of a specific module.

Ok, Let’s see a sample project to use Dagger2 in MVC Design pattern. In this sample project, we will store the article information into shared preference and fetched from shared preference to show the detail on view. First of all, you need to add some of the dependency into your build.gradle file as module level.

Java

1

2

3

4

compile"com.google.dagger:dagger:2.9"

annotationProcessor"com.google.dagger:dagger-compiler:2.9"

provided'javax.annotation:jsr250-api:1.0'

compile'javax.inject:javax.inject:1'

In the next step, we need to initialize the dagger builder in Main Application class.

Java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

publicclassMainApplicationextendsApplication{

protectedApplicationComponent mApplicationComponent;

@Override

publicvoidonCreate(){

super.onCreate();

setupInjector();

}

publicApplicationComponent getApplicationComponent(){

returnmApplicationComponent;

}

privatevoidsetupInjector(){

mApplicationComponent=DaggerApplicationComponent.builder()

.applicationModule(newApplicationModule(this)).build();

mApplicationComponent.inject(this);

}

publicstaticMainApplication get(Context context){

return(MainApplication)context.getApplicationContext();

}

}

Now you need to create your custom scope. As I am creating two scopes one is for @PerAppliction and other for @PerActivity.

Java

1

2

3

4

@Scope

@Retention(RetentionPolicy.RUNTIME)

public@interfacePerApplication{

}

Java

1

2

3

4

@Scope

@Retention(RetentionPolicy.RUNTIME)

public@interfacePerActivity{

}

In the next step, we need to create SharedPrefsUtil class as a @Singleton that we can reuse the Object throughout the application anywhere and will use a @Inject constructor for instantiating the object of this.

Java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

@Singleton

publicclassSharedPrefsUtil{

privateSharedPreferences mSharedPreferences;

publicstaticStringPREF_KEY="dagger_key";

@Inject

publicSharedPrefsUtil(SharedPreferences sharedPreferences){

mSharedPreferences=sharedPreferences;

}

publicvoidput(Stringkey,Stringvalue){

mSharedPreferences.edit().putString(key,value).apply();

}

publicStringget(Stringkey,StringdefaultValue){

returnmSharedPreferences.getString(key,defaultValue);

}

}

Now in the next step, I need to create module context based on Application and Activity Module.

Ok, You have done so for. I need to wrap up this post now otherwise it will go beyond this post. OMG for simple to store the Article information into the shared preference I have created so many classes for injecting dependency in MVP design.

The conclusion is that It does not matter how many class files need to create the most important that our code will be in well structured in MVP and Dagger2 and we do not worry about any refactor or changes in code in future.

Because Dagger divides the every module in a separate module that’s why it makes the Junit testing and changes in the code for a specific module is pretty easy and simple and every developer loving this. If you are using IntelliJ IDEA then use this plugin for a better debug experience. It will create visual connections between a @Inject object and the @Provides method that creates it.

I am a very enthusiastic Android developer to build solid Android apps. I have a keen interest in developing for Android and have published apps to the Google Play Store. I always open to learning new technologies. For any help drop us a line anytime at contact@mobologicplus.com

Categories

For better assist

Hey Folks, Welcome to the MobologicPlus blog. I’m Sunil Gupta, a tech blogger from Bangalore, India.
I started MobologicPlus as a passion, by helping people to understand the technical kinds of stuff from this blog. You have some feedback for MobologicPlus. Where should I send it? Sure, drop us a line anytime at contact@mobologicplus.com