Is it possible to use context isolation w/ a KMP l...
# koin
j
Is it possible to use context isolation w/ a KMP library using annotations? The problem I'm running into is how to properly initialize the KoinApplication with platform specific arguments such as Context for Android.. The Context Isolation example here has the application as a property on the "isolated context" so it's not possible to pass in the arguments. I could possible make the koinApp property a
lateinit
and enforce calling an "init" function at startup but that seems messy. Is there an obvious solution that I'm missing?
a
Main point here is to setup your "SDK entry point": the point of your app where your init Koin with
koinApplication
function. From this you have an isolated context, in the sense where it's not loaded in the main/static context.
if you need to pass an Android context parameter, you would need to request it from your SDK and pass it to your app context & initlization
j
I had a dedicated “Context” module but the issue was providing the context to my library appropriately. Since the
koinApp
is a property I couldn’t provide arguments to its initialization block. My workaround was to define an
init(ContextWrapper)
function MyIsolatedKoinContext object declaration and have it call an
expect/actual
function that in
androidMain/
will explicitly add a new
module
that holds the Android Context. Here is the function:
Copy code
actual fun KoinApplication.platformInitialize(espContext: ESPContext) {
    modules(
        module {
            espContext.appContext.also { appContext ->
                if (appContext is Application) {
                    single { appContext } bind (Context::class)
                } else {
                    single { appContext }
                }
            }
        }
    )
}