KDI is super lightweight Kotlin Multiplatform Manual DI library
Gradle
implementation("ru.astrainteractive.klibs:kdi:<version>")
Version catalogs
[versions]
klibs-kdi = "<latest-version>"
[libraries]
klibs-kdi = { module = "ru.astrainteractive.klibs:kdi", version.ref = "klibs-kdi" }
See also MobileX as parent library for more useful kotlin code
Firstly, create a module interface, which will contains necessary dependencies
/**
* This is your module with two dependencies
*/
interface PluginModule : Module {
val simpleDatabase: Single<Database>
val pluginTranslation: Single<PluginTranslation>
class Impl : PluginModule {
override val simpleDatabase: Single<Database> = Single {
TODO()
}
override val pluginTranslation: Single<PluginTranslation> = Single {
TODO()
}
}
}
/**
* Or you can use delegation to get rid of [Single] class
*/
interface DelegatePluginModule : Module {
val simpleDatabase: Database
val pluginTranslation: PluginTranslation
class Impl : DelegatePluginModule {
val simpleDatabase: Database by Single { TODO() }
val pluginTranslation: PluginTranslation by Single { TODO() }
}
}
/**
* This is your function, in which you need [PluginModule.simpleDatabase]
* and [PluginModule.pluginTranslation]
*/
fun myPluginFunction(module: PluginModule) {
TODO()
}
/**
* This is our custom subModule, which contains factory, which will return random UUID
*/
class SubModule : Module {
val randomUUID = Factory {
UUID.randomUUID()
}
}
/**
* This is our root module
*/
object RootModule : Module {
/**
* Here we getting via kotlin's ReadProperty SubModule;
*/
private val subModule = SubModule()
/**
* Here we remember uuid, provided by SubModule's factory
*/
val uuid = Single {
subModule.randomUUID.create()
}
}
That's it! As easy as it looks
Dependency
- is an interface which has getValueProperty, so can be used byval expression by dependency
Factory
- is a fun interface which can build data for your classesLateinit
- is used for components which can't be initialized internallModule
- is an interface is a definition for module package, which will containsProvider
- is a fun interface which can provider some data for your dependencyReloadable
- can be used to create reloadable components with kotlin objectSingle
- is a singleton value which will be a unique and single instant