Hey! I’ve been working with Koin for Compose for a while now and have a proposal to improve how
KoinContext
management works in
@Composable
functions. I believe the configuration of the Application should be done in the top level composable. This way it is not dependent on Koin initialization in the application class, which allows for easy
KoinContext
replacement in
@Preview
composables and tests. It introduces a new API -
Koin
and
KoinScope
composables:
@Composable
fun Koin(
appDeclaration: KoinAppDeclaration? = null,
content: @Composable () -> Unit
) {
val koinApplication = koinApplication(appDeclaration)
CompositionLocalProvider(LocalKoin provides koinApplication.koin) {
content()
}
}
@Composable
fun KoinScope(
getScope: Koin.() -> Scope,
content: @Composable () -> Unit
) {
val koin = getKoin()
val scope = remember {
koin.getScope()
}
CompositionLocalProvider(LocalScope provides scope) {
content()
}
}
I’ve opened PR here with implementation and instrumented tests:
https://github.com/InsertKoinIO/koin/pull/1178
On the screenshot there is an example how to use new API with Scope and Preview.
Pros:
- scopes works
- easy
KoinContext
replacement in tests
- easy
KoinContext
replacement in
@Preview
composables
- no need to use application class (which may help with Compose Multiplatform support in the future)
- backward compatibility (using GlobalContext as default value)