Android – Architecture – DI with Koin

Process of implementing Koin DI

Declare a module

Defines those entities which will be injected at some point in the app

val applicationModule = module {
  single { AppRepository }
}

Start Koin

A single line, startKoin(this, listOf(applicationModule)), allows you to launch the DI process and indicate which modules will be available when needed, in this case, only applicationModule

class BaseApplication : Application() {
  override fun onCreate() {
    super.onCreate()
    startKoin(this, listOf(applicationModule))
  }
}

Perform an injection

In consonance with Kotlin features, Koin allows to perform lazy injectionsin a very convenient way

class FeatureActivity : AppCompatActivity() {
  private val appRepository: AppRepository by inject()
    //...
}

Module, factory, single

Module

Module serves as a container for a collection of services that should be provided at runtime. You put all the services that a module should provide in the module block

val dataModule = module {

    single<SharedPreferenceManager>()

    single<ContactManager>()

    single { ContactServerManager(get()) }
}

Factory

A factory is a definition that will give you a new instance each time you ask for this object type. In other words, it represents a normal object. Any presenter involved in the application will be injected in the view instance in this way.

val splashModule = module {
    factory<SplashContract.Presenter> { (view: SplashContract.SplashView) -> SplashPresenter(view) }
}

Single

Single depicts a singleton component such as an instance that is unique across the application. This is typically intended for repositories, databases, etc.

The single definition does the exact opposite of the what factory does. It tells Koin to retain the instance and provide that single instance wherever needed. This can be done in some ways similar to the factory defined above. 

Be the first to comment

Leave a Reply

Your email address will not be published.


*