Stabbing the Dagger in Kotlin; merely in 4 mins

Chintan Soni
Jun 26, 2018 · 4 min read

Dagger, still one unsolved mystery to large number of Android Devs.

Their common question “How the heck Dagger works ?”

“Say no more, my friend…!!!”

Presuming, that you are aware with the concept of DI (Dependency Injection). If not, just go through this presentation of my talk at GDG Ahmedabad DevFest 2017, A (K)night with Dagger

This walk through is on Kotlin Development, not JAVA. I know “Old is Gold”, but “New is Platinum” 😍

Why do you need Dagger ?

In stone age, Dependencies demanded to be initialised in a sequence before being used (Courtesy: Our old friend, NPE!). For example,

class MyApplication : Application(){    var apiService : ApiService? = null    override fun onCreate() {
super.onCreate()

var file = getFile(context)
var cache = getCache(file)
var okHttpClient = getOkHttpClient(cache)
var gson = getGson()
var gsonConverterFactory = getGsonConverter(gson)
var retrofit = getRetrofit(okHttpClient, gsonConverterFactory)
var apiService = getRetrofitservice(retrofit)
}
fun getApiService() : ApiService? {
return apiService
}
}

Stuff was initialised at Application class or some utility class and then exposed with public / protected methods. But who were we kidding, huh? That thing was a mess. Just imagine of writing test-cases for it.

Well, with Dagger, life got much simpler.

Dagger drives your code more towards testable architecture for writing Unit Test cases.

Lets dig this shit!

Open your module-level gradle and add below lines:

Now, our dependencies will flow Application Level to Activities / Fragment.

Lets add the Dagger’s first ingredient Module, AppModule.kt.

This would be a class annotated with @Module. This is the place where object are created and are now ready to be injected. You can have more than one module in a project.

@Provides: This annotation is written above the methods that provides dependency. Example, provideApiService provides instance of ApiService interface to make api calls.

@Singleton: This annotation signifies a scope in which any instance will survive and is accessible within it. As the name suggests, this annotation creates an instance just once and reuses the same instance when and whenever required. Dagger retains those instances within it.

By now, your dependencies are ready to be injected. I am expecting ApiService object to be injected into Activity. But where to be injected is yet not defined. But why is it necessary ?

If you notice, in previous module, you provided dependencies by creating an object within a method. Now, do we create objects of any Activity ? Nope Obviously. Then, how would you inject dependencies into it ? 🤔

This is what Dagger has actually handled for you. Just go for it.

Lets add one more module, ActivityModule.kt

In this, you simply annotate the method with @ContributesAndroidInjector provided that method should be abstract, and hence, the class to have to be abstract. This way you are providing instance of HomeActivity so that HomeActivity can take part in DI.

In short, you can think this as a registry of Activities. You are registering your Activities for making it DI ready. You can make one such for Fragments, too.

Now, Lets add Dagger’s second ingredient Component, AppComponent.kt.

This would be an interface annotated with @Component. A Component is built on top of one or more modules. Modules can be linked to Component using “modules” attribute which is of type Array. Now, We attached AndroidSupportInjectionModule, AppModule and ActivityModule to AppComponent.

“But we didn’t create any such module AndroidSupportInjectionModule.”

Well, this module comes from Dagger-Android library, which helps Dependency Injection in Activity, Service, Receivers, Fragments (From Support Library), and ContentProviders. It means that you can inject any dependency into these Android Components.

“And, what does this snippet do in AppComponent ?”

@Component.Builder
interface Builder {
@BindsInstance
fun application(application: Application): Builder

fun build(): AppComponent
}

In brief, it generates a class DaggerAppComponent with Builder Pattern. It injects Application class instance into AppComponent. Now, you can use application instance where you want to use in Modules you have included into this component.

Lastly, we initialize AppComponent from within our app’s Application class as:

Points to ponder:

  • MyApplication class extends DaggerApplication.
  • Check the line that injects Application instance into AppComponent

That’s it. You are now READY to inject dependencies into Android Components. Lets see how.

Let your Activity extend DaggerAppCompatActivity instead of AppCompatActivity. And start injecting dependencies you want !!!

Now, you have instance of ApiService that is ready to be used. That’s it !!

Ever thought, stabbing Dagger into Kotlin, would be that easy 🙂

Shower your love ❤ if this article has helped you in any way. Claps are always welcome.

Credits: Thank you Paresh Mayani sir and Yash Soni for guiding me through this article.

Simform Engineering

Our Engineering blog gives an inside look at our…

Thanks to Paresh Mayani and Yash Soni

Chintan Soni

Written by

TechLead — Android at ARInspect | 7+ years of concrete experience in Android Development

Simform Engineering

Our Engineering blog gives an inside look at our technologies from the perspective of our engineers.

Chintan Soni

Written by

TechLead — Android at ARInspect | 7+ years of concrete experience in Android Development

Simform Engineering

Our Engineering blog gives an inside look at our technologies from the perspective of our engineers.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store