If I use KoinApplication to start Koin in commonMa...
# koin
f
If I use KoinApplication to start Koin in commonMain, how can I provide Android context? koin = 4.0.1
Copy code
Caused by: org.koin.core.error.NoDefinitionFoundException: No definition found for type 'android.content.Context'. Check your Modules configuration and add missing type and/or qualifier!
Does it mean that if I want to provide Android context I can't use KoinApplication in commonMain?
1
i
I just made a sample project trying it and went with something like this:
Copy code
@Composable
fun App(koinAppDeclaration: KoinAppDeclaration? = null) {
    KoinApplication(
        application = {
            koinAppDeclaration?.invoke(this)
            modules(appModule)
        }
    ) {
        MaterialTheme {
            MainScreen()
        }
    }
}
From all platforms you just call App function without the koinAppDeclaration and from Android you use it like this:
Copy code
setContent {
    App {
        androidLogger(Level.DEBUG)
        androidContext(this@MainActivity)
    }
}
Sorry for the formatting, I'm on the phone
f
Wow, that's great.Thank you very much for providing me with ideas.
👍 1
i
I pushed the code to a public GitHub repo: https://github.com/IgnacioCarrionN/KMPKoin
👍 1
g
would not that recreate koin when screen gets rotated?
i
This is the code in the KoinApplication composable function:
Copy code
@OptIn(KoinInternalApi::class)
@Composable
fun KoinApplication(
    application: KoinAppDeclaration,
    content: @Composable () -> Unit
) {
    val koin = rememberKoinApplication(koinApplication(application))
    CompositionLocalProvider(
        LocalKoinApplication provides koin,
        LocalKoinScope provides koin.scopeRegistry.rootScope,
        content = content
    )
}
It uses remember and CompositionLocalProvider to provide the Koin instance. I'm pretty sure that with recompositions will not recreate the Koin instance but I'm not sure in the case of screen rotation.
f
After update 4.1.0-Beta5,I can use KoinMultiplatformApplication to start Koin.It looks like this:
Copy code
@Composable
@Preview
fun App() {
    KoinMultiplatformApplication(
        config = koinConfiguration {
            defaultModule()
            modules(
                PlatformModule.module,
                AppModule.module
            )
        }
    ) {
            MainScreen()
    }
}