Hi everyone, I'm working on my KMP project and I'v...
# multiplatform
p
Hi everyone, I'm working on my KMP project and I've run into an issue with initializing classes via Koin when they have different constructor requirements based on the platform. For example, imagine I have a class that needs an Android Context in its constructor for the Android target, but obviously not for the iOS target. How can I inject the same object (defined by an interface) using Koin, while delegating the actual implementation and its specific constructor dependencies to each individual platform (Android and iOS)? Thanks
o
Maybe you can follow the pattern used by Room. On Android you need to provide a context, not for desktop for instance.
(not for iOS either obviously)
q
I typically implement one of these two solutions: 1. Declare a singleton or static variable to store the current context. Instead of passing the context around, directly access it via this variable when needed. 2. Define an interface class in commonMain, then have androidMain, iosMain, or even Swift code in iosApp implement it separately, and pass the implementation to Kotlin for invocation.
v
This is more of a #C67HDJZ2N question as far as I see. Specifically with Koin, you can create an expect/actual module that creates said interface:
Copy code
commonMain:
expect fun createPlatformModule(): Module

androidMain:
actual fun createPlatformModule(): Module = module {
    single<Foo> { AndroidFoo(context = get()) }
}

iosMain:
actual fun createPlatformModule(): Module = module {
    single<Foo> { IosFoo() }
}
Dont' forget to pass the androidContext in
startKoin
on the Android's side.
Copy code
startKoin {
    androidContext(...)
}
If you have
startKoin
in a shared place, expose a lambda
KoinApplication.() -> Unit
to be able to add additional modules for a specific platform.
Copy code
fun initialize(action: KoinApplication.() -> Unit) {
    startKoin {
        action()
        modules(
            listOf(createPlatformModule(), ...)
        )
    }
}
p
Ohh thanks a lot of all of u. Cool solution