DI with Koin — Introduction and Implementation
It is a smart Kotlin Dependency Injection Library.
Its features are:
- Light weight
- Easy to learn
Terminology:
- module — it creates a module in Koin which would be used by Koin to provide all the dependencies.
- single — it creates a singleton that can be used across the app as a singular instance.
- factory — it provides a bean definition, which will create a new instance each time it is injected.
- get() — it is used in the constructor of a class to provide the required dependency.
Implementation:
Gradle Setup:
// koin
// Koin main features for Android (Scope,ViewModel ...)
implementation "io.insert-koin:koin-android:${koin_version}"
// Koin Android - experimental builder extensions
implementation "io.insert-koin:koin-android-ext:${koin_version}"
// Koin for Jetpack WorkManager
implementation "io.insert-koin:koin-androidx-workmanager:${koin_version}"// Current version
koin_version= "3.0.1-beta-2"
Create Your Components:
Service
interface KoinService {
fun provideService(): String
}
Repository
class KoinRepository : KoinService {
override fun provideService(): String = "Provide Koin Service 1"
}
ViewModel
class KoinViewModel(val repo: KoinRepository) : ViewModel(){
fun doSomethingWithService() = repo.provideService()
}
Declare the Koin Module:
val appModule = module { // single instance of KoinRepository
single<KoinService> { KoinRepository() } // KoinViewModel
viewModel { KoinViewModel(get()) }
}
Start Koin From your Application Class:
class MyApp : Application() {
override fun onCreate() {
super.onCreate() startKoin {
androidLogger()
androidContext(this@NotifyMeApp)
modules(appModule)
}
}}
Finally you can Inject the Dependency and use it:
class KoinActivity : AppCompatActivity() { //lazy inject viewmodel
val myViewModel: KoinViewModel by viewModel() override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_first)
// use your viewmodel here
myViewModel.doSomethingWithService()
}
}