Hi, how can I do Koin injection in iOS side? Tried <https://medium.com/@uwaisalqadri/elegant-koin-in...
h
s
This is just my own approach, so no more authoritative than any blog post, but:
Kotlin shared:
Copy code
/**
 * Multi-platform wrapper around Koin.
 * Provides an init method that can be called from each platform entrypoint, and Swift-compatible getters.
 */
object ServiceContainer : KoinComponent {
    var koinApplication: KoinApplication? = null
        private set

    /**
     * Initializes the Koin DI container
     *
     * @param [platformContext]
     * A platform-specific context object. On Android, this should be the app Context. On iOS it is unused.
     */
    fun start(platformContext: Any?) {
        if (koinApplication != null) return

        koinApplication = startKoin {
            useLogger()
            usePlatformContext(platformContext)
            modules(rootModule)
        }
    }

    fun start() {
        start(null)
    }
}
iOS Kotin:
Copy code
/*Define extension methods on ServiceContainer for any values SwiftUI code might need to inject directly */
fun ServiceContainer.messageBus(): MessageBus = get()
//Etc...
SwiftUI:
Copy code
//App is wrapped in this
struct WithServiceContainer<Content : View> : View {
    let content: () -> Content

    init(@ViewBuilder content: @escaping () -> Content) {
        self.content = content
        ServiceContainer.shared.start()
    }

    var body: some View {
        content()
    }
}

//Then just do e.g.
let messageBus: MessageBus = ServiceContainer.shared.messageBus()
k
In KaMPKit we use this https://github.com/touchlab/KaMPKit/blob/main/shared/src/commonMain/kotlin/co/touchlab/kampkit/Koin.kt https://github.com/touchlab/KaMPKit/blob/main/ios/KaMPKitiOS/Koin.swift In common code, we have a
coreModule
and then an expect / actual
platformModule
for iOS. Then we init koin from Swift
h
will try both of these thank you
464 Views