Jeff Lockhart
02/13/2024, 7:55 AMKoinApplication(application = { ...
as described here. But the Android app sometimes 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.I'm assuming this happens when the Activity is recreated, as this is where the composable
App
is launched and where the stack trace stems from. Shouldn't KoinApplication
expect this behavior of Activity recreation on Android?Nino
02/13/2024, 11:06 AMJeff Lockhart
02/13/2024, 3:12 PMKoinApplication
can be used in an Android Jetpack Compose App()
composable, which is started from an `Activity`'s setContent
, not from the Android Application
?
> Else if you want to start a new Koin instance from your Compose app, The function KoinApplication
helps to create Koin application instance, as a Composable. This is a replacement of the classic startKoin
application function.Jeff Lockhart
02/16/2024, 6:07 PMKoinApplication(application = { ...
should be used in an Android Compose app? The documentation isn't clear how this should be expected to be called from an Activity
.youssef
02/17/2024, 9:01 AMoverride fun onDestroy() {
super.onDestroy()
stopKoin()
}
Jeff Lockhart
02/18/2024, 2:12 AMActivity
lifecycle then. In that case, I'd prefer to stick with startKoin
in the Application
rather than using this KoinApplication
API on Android.Joel Denke
02/19/2024, 9:04 AMJoel Denke
02/19/2024, 9:08 AM@Composable
@Throws(ApplicationAlreadyStartedException::class)
fun KoinApplication(
application: KoinAppDeclaration,
content: @Composable () -> Unit
) {
val koinApplication = remember(application) {
val alreadyExists = KoinPlatformTools.defaultContext().getOrNull() != null
if (alreadyExists) {
throw ApplicationAlreadyStartedException("Trying to run new Koin Application whereas Koin is already started. Use 'KoinContext()' instead of check for any 'startKoin' usage. ")
} else {
startKoin(application)
}
}
CompositionLocalProvider(
LocalKoinApplication provides koinApplication.koin,
LocalKoinScope provides koinApplication.koin.scopeRegistry.rootScope
) {
content()
}
}
See https://github.com/InsertKoinIO/koin/blob/main/projects/compose/koin-compose/src/commonMain/kotlin/org/koin/compose/KoinApplication.kt how they achieve things 🙂 Documentation I agree is not very clear for compose scenarios.Joel Denke
02/19/2024, 9:10 AMJeff Lockhart
02/19/2024, 3:37 PMstartKoin
in the Application
and using KoinAndroidContext
to wrap the Compose app.