0

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, effectively 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

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(
                    listOf(listOfModules),
                )
            }
        } else {
            startKoin {
                modules(listOfModules)
            }
        }

    val koin = koinApp.koin
}

And i extend the KoinScopeComponent like this

interface MyKoinComponent : KoinComponent {

    // Override default Koin instance
    override fun getKoin(): Koin = KoinInstance.koin
}

I initilize koin like this: 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?

1 Answer 1

0

After some help from the guys at the #koin channel in the kotlinlng slack, i relized i dont need to call startkoin at all and i can just call my isolated context

object KoinInstance {
    val koinApp = koinApplication {
        modules(
            listOf(
                appModule,
                databaseModule,
                networkModule,
                repositoryModule,
                coroutineModule,
                syncModule,
            ),
        )
    }

    val koin = koinApp.koin
}

This allows me to call stopKoin and clear my classes without worrying about it affecting the consumer app

Not the answer you're looking for? Browse other questions tagged or ask your own question.