1. 程式人生 > >How to use Dagger 2 on Android with Kotlin (KAD 20)

How to use Dagger 2 on Android with Kotlin (KAD 20)

Virtually everyone who wants to create code on Android in a decoupled and easy-to-test way, resorts to Dagger sooner or later.

Although there is something that works a bit differently when setting up Dagger in Kotlin, most of it is quite simple, and in a few steps I’m going to show you here today.

Also be aware that, thanks to

the power of Kotlin, there are other ways to solve the injection, and even some libraries made exclusively in Kotlin for it.

But Dagger remains a perfectly valid option, and one of the most versatile (if not the most).

Disclaimer: In this article I won’t explain how Dagger 2 is used, this is already known. If you have any questions, I wrote

some articles about dependency injection a while ago.

Configuring the project to use Dagger 2

If you’ve already configured the Kotlin plugin in your project, all you need to do is configure kapt.

If you already used Dagger, you probably know apt. kapt is just the version for Kotlin, which creates the necessary self-generated classes for Dagger.

To configure it, you need to add the following to build.gradle:

Want to learn Kotlin?

Check my free guide to create your first project in 15 minutes!

123 kapt{generateStubs=true}

You can add it just before the dependencies section. If you want, you can instead use the new experimental plugin, which is pretty stable already:

12 apply plugin:'kotlin-kapt'

Now you just need to add the dependencies of the Dagger compiler (using kapt to not be included in the apk) and the actual library:

12 kapt'com.google.dagger:dagger-compiler:2.5'compile'com.google.dagger:dagger:2.5'

Everything is ready to start using Dagger.

Main module implementation

As you may know, for the main graph you’ll need a Module and a Component.

The application module, in this simple example, will only return the instance of the application itself.

To do this we’ll create a class annotated with @Module, which will receive the application instance via constructor, store it in a property, and return it using a method annotated with @Provides @Singleton:

123 @Module classAppModule(val app:App){@Provides@Singleton fun provideApp()=app}

You can see that, even for this easy class, the code is much simpler than in Java.

Now we have to implement the Component, which needs an array of modules to load, and specifies who is going to be able to manually inject it:

12345 @Singleton@Component(modules=arrayOf(AppModule::class))interfaceAppComponent{fun inject(app:App)}

Just create the class App, which will be responsible of generating the graph:

1234567891011121314 classApp:Application(){val component:AppComponentbylazy{DaggerAppComponent.builder().appModule(AppModule(this)).build()}override fun onCreate(){super.onCreate()component.inject(this)}}

The interesting thing to see here is that, thanks to the lazy statement, we can specify the value of the graph in the definition of the property, and thus get read-only access to that property.

The code defined by the property won’t be executed until component.inject (this) is done, so that by that time this already exists and can be created securely way.

One module implementation per scope

The modules by scope allow that part of the graph only to live during the lifetime of the object that creates it.

We would create our module with what we need:

123 @ModuleclassHomeModule(val activity:HomeActivity){}

A Subcomponent in a very similar way to the previous one, indicating that it’ll be injected into the HomeActivity:

12345 @Singleton@Subcomponent(modules=arrayOf(HomeModule::class))interfaceHomeComponent{fun inject(activity:HomeActivity)}

And a plus method in AppComponent, to indicate that this component can be added subcomponents of that type:

1234 interfaceAppComponent{...fun plus(homeModule:HomeModule):HomeComponent}

Now, in the HomeActivity you only need to declare the subcomponent:

1 valcomponentbylazy{app.component.plus(HomeModule(this))}

And you can inject it after the setContentView:

12345 override fun onCreate(savedInstanceState:Bundle?){super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)component.inject(this)}

If you’re wondering where app comes from, it’s a extension property that looks like this:

12 val Activity.app:Appget()=application asApp

It’s simply a way to avoid having to do casting every time you access application if you have your own custom one.

Conclusion

Dagger 2 is also easy to use in Kotlin. You no longer have an excuse to implement a great decoupled architecture in Kotlin.

If you want to learn a lot more about all of this and create your own Android Apps in Kotlin, take a look at the free guide to learn how to build your first project, or just get the book and learn how to create a complete App from scratch.

I’m in love with Kotlin. I’ve been learning about it for a couple of years, applying it to Android and digesting all this knowledge so that you can learn it with no effort.

Shares

Like this:

Like Loading...

相關推薦

How to use Dagger 2 on Android with Kotlin (KAD 20)

Virtually everyone who wants to create code on Android in a decoupled and easy-to-test way, resorts to Dagger sooner or later. Although there is some

How to make unit test on Android with Kotlin (KAD 22)

Of course, Kotlin also allows us to do unit tests in a very simple way, and very similar to what we’re used in Java. There are some small complicatio

How to use Retrofit on android with Kotlin (KAD 21)

This is just one more example about how in Kotlin we can continue to use the same libraries we’ve always used in Java for Android. Retrofit is a libr

How to use for ASP.NET Core with csproj

2017-10-10 23:40:29.5143||DEBUG|ASP.NET_Core_2___VS2017.Program|init main 2017-10-10 23:40:30.9739|0|INFO|Microsoft.AspNetCore.DataProtection.KeyManageme

How To Create Custom Dialog In Android With Validation

Let’s learn how to create custom dialog in android and while we are at it, let us also do simple validation of the data the user entered before clicking

How to use common workflows on Amazon SageMaker notebook instances

Amazon SageMaker notebook instances provide a scalable cloud based development environment to do data science and machine learning. This blog post

How to do Deep Learning on Graphs with Graph Convolutional Networks

Observe that the weights (the values) in each row of the adjacency matrix have been divided by the degree of the node corresponding to the row. We apply th

How to create beautiful pipelines on Elixir with Opus

Use caseAt Quiqup, we have a business model that requires our drivers to perform different kinds of work. For example, depending on who is ordering, our dr

How to Use Metrics for Deep Learning with Keras in Python

Tweet Share Share Google Plus The Keras library provides a way to calculate and report on a suit

Custom Views in Android with Kotlin (KAD 06)

When we saw the article about classes, you may remember that in general only one constructor is used. This is a problem for creating custom views. Th

How to use Context with Dialogflow to handle errors (Part 2: Knock Knock, It’s me)

How to use Contextual Fallback with Dialogflow to handle errors (Part 2: Knock Knock Jokes)(This is Part 2 of a four-part series on how to use Context with

How to Use an SSL Certificate on ACM or IAM with CloudFront

{ "Version": "2012-10-17", "Statement": { "Effect": "Allow", "Action": [ "acm:ListCertificates",

How to install Hadoop 2.7.3 cluster on CentOS 7.3

大數據############################# #ENV #spark01 192.168.51.6 #spark02 192.168.51.18 #spark03 192.168.51.19 #spark04 192.168.51.21 #spark05 192.168.51.24 ###

[RxJS] Learn How To Use RxJS 5.5 Beta 2

toarray return ray erro bsp err source val com The main changes is about how you import rxjs opreators from now on. And introduce lettabl

How to use Kata Containers and CRI (containerd plugin) with Kubernetes

bsp use k8s doc ner blob ber uber net https://github.com/kata-containers/documentation/blob/master/how-to/how-to-use-k8s-with-cri-contain

How to use Toyota simulated card + P001 Programmer with Obdstar X300 DP PLUS

Obdstar X300 DP Plus OBDSTAR X300 DP Plus key programmer OBDSTAR X300 DP plus PAD X300 DP Plus Purpose: To check if OBDSTAR X300 DP PLUS can

How to Use vcpkg On Windows

Introduction If you do any sort of C++ development on Windows, then you know that library/package management can be quite a pain at times (ever built Open

How to inject mock dependencies into Android components using Dagger AndroidInjector

How to inject mock dependencies into Android components using Dagger AndroidInjector https://android.jlelse.eu/how-to-inject-mock-dependencies-into-

How To Use Retrofit Library In Your Android App

Retrofit library is a Type-safe REST client for android and Java, courtesy of Square Inc. Most modern android apps make HTTP requests to some remote s

How to Use Local Keywords to Rank Higher on Google

Many strategies can help you rank better for competitive keywords related to your product and industry. However, one often overlooked factor is local SEO.