I'm using Koin in a KMM project. On Android it's working as expected but on iOS I have to create a wrapper around each component I want to inject, something like this (Logger component as an example):
inline fun <reified T> getKoinInstance() =
object : KoinComponent {
val value: T by inject()
}.value
object LoggeriOS {
private val logger = getKoinInstance<Logger>()
fun logger() = logger
}
Then I can do this on iOS:
let logger = LoggeriOS.shared.logger()
logger.i(msg: "Hello World")
Question: is there a better way to do this without a wrapper class specifically for iOS?
You can directly provide extensions to Koin class from kmm module and then in ios side directly use them.
Step 1 Define extension for Inside kmm ios module
val Koin.logger: Logger
get() = get() // second get() is from koin
Step 2
And then define method for starting koin from ios side, Koin.swift file and save global instance of koin
func startKoin() {
let koinApplication = DependencyInjectionKt.doInitKoinIOS()
// _koin is Koin instance
_koin = koinApplication.koin
}
//koin is a global instance of Koin, use it to get dependencies
private var _koin: Koin_coreKoin? = nil
var koin: Koin_coreKoin {
return _koin!
}
Step 3 And then in iosApp.swift file
@main
struct iOSApp: App {
init() { startKoin() }
}
ANd then you can use koin instance from Koin.swift anywhere just like this
koin.logger // this will use the extension you defined in kmm module in first step and will provide you Logger
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With