https://kotlinlang.org logo
Title
h

Hasan Nagizade

04/12/2023, 6:46 PM
s

Sam

04/12/2023, 6:56 PM
This is just my own approach, so no more authoritative than any blog post, but:
Kotlin shared:
/**
 * 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:
/*Define extension methods on ServiceContainer for any values SwiftUI code might need to inject directly */
fun ServiceContainer.messageBus(): MessageBus = get()
//Etc...
SwiftUI:
//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

Kevin S

04/12/2023, 9:42 PM
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

Hasan Nagizade

04/13/2023, 8:00 AM
will try both of these thank you