Working with Contexts

Separation logic within your module

A context is a logical subset of bean definitions inside a module:

val myModule = applicationContext {
    context("myContext"){
        bean { MyComponentA() }
        bean { MyComponentB(get()) }
    }
}

Handling components lifecycle

The primary target of a context is the ability to drop its instances,in order to suits your components life cycle. This is usefull when you can’t use a factory bean definition, and must share instances for a given timelife. Thus you can provide singletons and drop them when you don’t need them anymore.

The releaseContext() function release all instances from a context. Below an Android example:

i.e: in an Android Activity:

abstract class MyCustomActivity : AppCompatActivity() {

    abstract val contextName: String

    override fun onPause() {
        releaseContext(contextName)
        super.onPause()
    }
}

Context isolation

Context isoloation is unabled by default. It can be activated with Koin.useContextIsolation=true, before calling your startKoin() function. It will allow the given visibility rules. Rootcontext is the context from the root, directly at applicationContext level.

val myModule = applicationContext {
    context("A"){
        context("B"){
            
        }    
    }
    context("C"){
        
    }
}
  • beans inside B can see beans from A and Root - can’t see beans from C
  • beans inside A can see beans from Root, can’t see beans from B or C
  • beans inside C can see beans from Root, can’t see beans from A or B