Forget Dagger 2, Koin is a game changer

Times ago Google released Dagger 2 framework to simplify the implementation of dependency injection on Android. Everybody was exited but the things have changed. Nowadays Android Developers have the new DI framework for Kotlin which makes it easier to implement, less boilerplate code and more lightweight than Dagger 2.The first impression for me was awesome.

Starting up:

Add Koin Library, with just one line:

Implementation ‘org. Koin: Koin-android: 0.9.1’

As an android framework Koin needs to start on application class. We need to call the startKoin() method.

Declaring the modules:

val myModule: Module=org.koin.dsl.module.applicationContext {
factory { MyPresenter(get()) } // get() will resolve Repository instance
bean { MyRepository() as Repository }
}

Koin has five main keywords:

  • get — retrieve a component, for provided definition function
  • bind — declare an assignable class or interface to the provided component
  • factory — declare a factory instance component (new instance on each demand)
  • bean — declare a singleton instance component (unique instance)
  • applicationContext — declare your Koin application context

The moment when I inject:

val presenter : MyPresenter by inject()

As Dagger we can inject into class or direct into the constructor.

If you would like to get in touch, ping me via Github or LinkedIn.