In a Compose Multiplatform app for Android+iOS, I'...
# koin
b
In a Compose Multiplatform app for Android+iOS, I'm starting Koin as described in the docs here. But on Activity recreation the Android app crashes with:
org.koin.core.error.KoinAppAlreadyStartedException: Trying to run new Koin Application whereas Koin is already started. Use 'KoinContext()' instead of check for any 'startKoin' usage.
This can be reproduced by pressing back so the Activity goes into the background and is stopped, then returning to it. This crash has been discussed here before: https://kotlinlang.slack.com/archives/C67HDJZ2N/p1707810902616629 My solution to this for now is using an isolated context (docs), since I don't want to use platform specific solutions to starting koin from an application level, and having the koinApplication being created in an object prevents it from being recreated with the main composable, i.e. preventing the crash. Q1: Are there any downsides to this solution I should be aware of? Q2: Will there be an update to the docs or a bugfix so this crash does not happen anymore?
☝️ 1
a
Hello, do you use
startKoin
in your application class?
KoinAndroidContext will bind on current context for Android. It can be started previously with
startKoin
and you should not need to recreate it
b
No, I didn't want to do it in the Application class, because then I would have to start it somewhere else for iOS as well. I wanna see how far I can go with only shared code for at least Android + iOS.
a
interesting. You are using
KoinContext
composable then?
b
This is how I am using it now:
Copy code
@Composable
fun App() {
    KoinIsolatedContext(context = MyIsolatedKoinContext.koinApp) {
        AppContent()
    }
}

@Composable
fun KoinIsolatedContext(
    context: KoinApplication,
    content: @Composable () -> Unit
) {
    CompositionLocalProvider(
        LocalKoinApplication provides context.koin,
        LocalKoinScope provides context.koin.scopeRegistry.rootScope
    ) {
        content()
    }
}
a
You could use
KoinIsolatedContext
from Koin and even
KoinContext
. This last won't throw exception on restart like
KoinApplication
b
Thanks! Looks like all I needed to do was this 😊
Copy code
@Composable
fun App() {
    KoinContext(context = koinApplication {
        modules(sharedKoinModule)
    }.koin) {
        AppContent()
    }
}
🎉 1
199 Views