Hasan Nagizade
04/12/2023, 6:46 PMSam
04/12/2023, 6:56 PMSam
04/12/2023, 6:58 PM/**
* 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()
Kevin S
04/12/2023, 9:42 PMcoreModule
and then an expect / actual platformModule
for iOS. Then we init koin from SwiftHasan Nagizade
04/13/2023, 8:00 AM