Stabbing the Dagger in Kotlin; merely in 4 mins

Chintan Soni
Simform Engineering
4 min readJun 26, 2018

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.

Note: Dagger doesn’t help improve your App’s Performance. But it helps make your code more Testable, Manageable and Memory Efficient (to some extent, Scopes!!).

Lets dig this shit!

Open your module-level gradle and add below lines:

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

Dagger Ingredients

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

1. Module:

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.

2. Component

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.

--

--

Chintan Soni
Simform Engineering

Engineering Manager | 10+ years of experience | Android | Angular | NodeJS | React | Docker