Search code examples
androidkotlindependency-injectionkoin

startKoin crash, library


Recently I published a library with koin; when I used this library in my own application, everything is ok because I don't use Koin in my application, but if I startKoin in my application and the library both, the app crashes!.

Is there any way to use koin in application and library same? how can I call startKoin in my library without facing any problem in apps that used koin and called startKoin?

org.koin.core.error.KoinAppAlreadyStartedException: A Koin Application has already been started


Solution

  • After some research, I found that I should use a custom KoinComponent.

    Based on the documentation:

    For SDK Makers, you can also work with Koin in a non global way: use Koin for the DI of your library and avoid any conflict by people using your library and Koin by isolating your context

    // create a KoinApplication
    val myApp = koinApplication {
    // declare used modules
    modules(coffeeAppModule)
    }
    

    And keep myApp in a object:

    // Get a Context for your Koin instance
    object MyKoinContext {
    var koinApp : KoinApplication? = null
    }
    
    // Register the Koin context
    MyKoinContext.koinApp = KoinApp 
    

    and then :

    interface CustomKoinComponent : KoinComponent {
    // Override default Koin instance, intially target on GlobalContext to yours
    override fun getKoin(): Koin = MyKoinContext?.koinApp.koin
    

    }

    And now, you register your context and run your own isolated Koin components:

    MyKoinContext.koinApp = myApp
    
    class ACustomKoinComponent : CustomKoinComponent(){
    // inject & get will target MyKoinContext
    }
    

    more info