Koin: What is the proper way to use androidApplication()?

Created on 13 Aug 2018  路  5Comments  路  Source: InsertKoinIO/koin

I'm wondering what is the best way to use androidApplication() method to get application context.

Basically, I have a file called Modules.kt:

val applicationModule = applicationContext {
    // Feature Adapter
    bean { FeatureAdapter(androidApplication()) }

    // Feature Loader
    bean { FeatureConverter(androidApplication()) }

Checking documentation, I can see androidApplication() runs get() which has a O(n) complexity.

I'm wondering if there are any problem by declaring a context val in beginning of my class, like this:

val applicationModule = applicationContext {
    val context = androidApplication()

    // Feature Adapter
    bean { FeatureAdapter(context) }

    // Feature Loader
    bean { FeatureConverter(context) }
question

Most helpful comment

Im currently unable to reference androidApplication() or androidContext() in my module definitions and get instance creation exceptions. Im calling startKoin from a java application class.

All 5 comments

Both are ok

Closing question issue - Please reopen it or post your next question on stackoverflow: https://stackoverflow.com/questions/tagged/koin

Im currently unable to reference androidApplication() or androidContext() in my module definitions and get instance creation exceptions. Im calling startKoin from a java application class.

@arnaudgiuliani As @scottkruse mentioned with koin2.0.1 we cannot access androidApplication() or androidContext(). How are we supposed to get Application dependency for other components with latest library?

By starting Koin anbd supplying the context, a single bean is registered for you with the application context.

    startKoin {
        androidContext(this@MyApplication)
        modules(allMyModules)
    }

After that you can inject it like any other dependency, no magic or extra function required.

val applicationModule get() = module {
    single { SomeThingThatNeedsContextAsParam(get()) }
}
Was this page helpful?
0 / 5 - 0 ratings

Related issues

hkelidari picture hkelidari  路  3Comments

miladsalimiiii picture miladsalimiiii  路  3Comments

ILAgent picture ILAgent  路  3Comments

LukasAnda picture LukasAnda  路  3Comments

Jeevuz picture Jeevuz  路  4Comments