I am using koin in an SDK, i create an isolated ko...
# koin
z
I am using koin in an SDK, i create an isolated koin context as explained in the docs, however, i want to allow the SDK consumer to turn the SDK off, effectivly clearing all classes created by the SDK, however, if i call
stopKoin
or
close()
, and u try to init the SDK again, it will crash with
org.koin.core.error.ClosedScopeException: Scope '_' is closed
I assume i need to use scopes here but i find it hard to understand from the docs, how i can incorporate scopes into my structure. I have an object called
KoinInstance
Copy code
object KoinInstance {
    
    val isGlobalKoinStarted: Boolean
        get() = try {
            GlobalContext.get() // Attempts to get the global Koin context
            true // If it succeeds, Koin has been started
        } catch (e: Exception) {
            false // If it fails, Koin has not been started
        }

    val koinApp = if (isGlobalKoinStarted) {
            koinApplication {
                modules(myModules)
            }
        } else {
            startKoin {
                modules(myModules)
            }
        }

    val koin = koinApp.koin
}
And i extend the
KoinScopeComponent
like this
Copy code
interface MyKoinComponent : KoinComponent {

    // Override default Koin instance
    override fun getKoin(): Koin = KoinInstance.koin
}
I initilize koin like this:
Copy code
KoinInstance.koinApp.androidContext(context.applicationContext)
This works well until i try to call `close`/`unloadModules`/`stopKoin` to remove my classes and init the KoinApp again. Any idea how i can incorporate scopes into this approach?
a
Why trying to start global/isolated instance here? In case of SDK start only isolated instance. Else you will fall in case of trying to close elements from outside your SDK.
👀 1
z
I see, if i only start with koinApplication { modules(myModules) } I can safly call stopKoin?
a
yes
✅ 1
w
I'd be careful, if any of your consumers are using a different Koin version it's likely to break their application unless they match versions with you https://kotlinlang.slack.com/archives/C67HDJZ2N/p1720712694679259
109 Views