cover by Koin developers

Skipping from Dagger to Koin

After many times trying to learn Dagger I finally found a way to run out of it. Koin just saved my life and is making it easy.

I have ben spend some time trying to learn Dagger, somehow it was very hard to understand the concept, how it works and how to use. After some time searching for a good tutorial to learn it, I found Koin.

What is Koin?

“ A pragmatic lightweight dependency injection framework for Kotlin developers. Written in pure Kotlin using functional resolution only: no proxy, no code generation, no reflection.”

Those two highlighted words are the disadvantage of Dagger. Also this article made me understand more about some problems with it. That is why I’m skipping to Koin, it is more simple and easy to learn.

Note: Please understand that I’m not here to judge any framework, it is my experience with dependency injection on Android. You are free to chose witch one is more easy and simple for you or your team.

How to use Koin?

I want to show you a simple example of how Koin works in a real Android Project, also how it is simple to use.

Note: some code was removed for brevity. See the complete code here.

  1. Some class to be Injected, in this case we have the repository class.

2. The ViewModel receiving the Repository class as dependency.

3. Dependency Modules. Here we initialize ours classes, so that Koin will take care about how to bind with others as dependency.

4. In our application class we initialize the Koin framework. We need to provide the modules that we want to use. In case we have only one Module so we pass it.

We’re done, after this steps we can now use our classes by injecting it with Koin. Below is a example of how can we use our classes in an Activity:

We have a project where we get some data from Repository class that is a dependency of our ViewModel, then we get ViewModel instance by dependency injection using Koin in our Activity. Displaying a toast with the message coming from Repository class.

What if I’m using Java?
Koin also support java files, so don’t worry about it. Just check the documentation to see more.

And…

I found it very good, I recommend to try and get your own conclusions. Do not forget to look at the official documentation for a complete understanding since this was just a showcase.

So much easy. with two simple steps we have Koin ready to work with us. Check the complete code: https://github.com/pedromassango/android-koin