Multiple Koin Modules in Android
This guide covers Android-specific module organization and loading strategies. For core module concepts (module declaration, includes, overrides), see Modules.
Loading Modules in Android
In Android, you typically load Koin modules in your Application class's onCreate() method:
class MainApplication : Application() {
override fun onCreate() {
super.onCreate()
startKoin {
androidLogger()
androidContext(this@MainApplication)
// Load your modules
modules(appModule, networkModule, dataModule)
}
}
}
You can organize modules by feature, layer (data/domain/presentation), or Gradle module - whatever makes sense for your app architecture. For multi-module app organization patterns, see Multi-Module Apps.
Reducing Startup time with background module loading
You can declare "lazy" Koin modules to avoid triggering any pre-allocation of resources and load them in parallel background coroutines. This helps avoid blocking the Android startup process and significantly reduces startup time when you have multiple modules.
Key Features
lazyModule- declare a Lazy Kotlin version of Koin ModuleModule.includes- allow to include lazy ModulesKoinApplication.lazyModules- load lazy modules in parallel background coroutines (each module in its own job)Koin.waitAllStartJobs- wait for all start jobs to completeKoin.runOnKoinStarted- run block code after start completion
Parallel Loading Performance (4.2.0+)
Starting from version 4.2.0, lazy modules are loaded in parallel, with each module getting its own coroutine job. This dramatically improves startup time:
// Multiple lazy loaded modules - all load in PARALLEL!
val databaseModule = lazyModule {
singleOf(::DatabaseService)
}
val networkModule = lazyModule {
singleOf(::NetworkService)
}
val analyticsModule = lazyModule {
singleOf(::AnalyticsService)
}
val coreModule = module {
singleOf(::CoreService)
}
class MainApplication : Application() {
override fun onCreate() {
super.onCreate()
startKoin {
androidLogger()
androidContext(this@MainApplication)
// Core module loads immediately
modules(coreModule)
// All lazy modules load in parallel in background
lazyModules(databaseModule, networkModule, analyticsModule)
}
}
}
Performance Impact:
- With 10 modules that each take 100ms to load:
- Before 4.2.0: ~1000ms (sequential)
- After 4.2.0: ~100ms (parallel)
Waiting for completion
You can wait for all lazy modules to finish loading before proceeding:
val koin = KoinPlatform.getKoin()
// Block until all background loading is complete
koin.waitAllStartJobs()
// or run code after loading completes
koin.runOnKoinStarted { koin ->
// All lazy modules are now loaded
koin.get<AnalyticsService>().trackAppStart()
}
See Lazy Modules Documentation for more details on parallel loading and multiplatform support