Member-only story
Integrating Koin Dependency Injection with Jetpack Compose in Android

Jetpack Compose has revolutionized Android development by simplifying UI creation with a declarative approach. Pairing it with a dependency injection library like Koin makes managing dependencies seamless and scalable. In this article, we’ll walk through integrating Koin with Jetpack Compose in an Android project using Gradle Kotlin DSL (KTS).
Why Koin?
Koin is a lightweight dependency injection (DI) library designed specifically for Kotlin. Its simplicity, ease of integration, and Compose-friendly tools make it an excellent choice for managing dependencies in modern Android apps.
Step 1: Add Koin Dependencies
To get started, include Koin’s dependencies in your build.gradle.kts
file (module-level):
dependencies {
// Koin for Jetpack Compose
implementation("io.insert-koin:koin-androidx-compose:3.5.0")
}
This dependency enables Koin integration with Compose.
Step 2: Define Koin Modules
Koin modules are used to declare dependencies. Create a KoinModule.kt
file and define a module with your dependencies:
import org.koin.androidx.compose.koinViewModel
import org.koin.dsl.module
val appModule = module {
// Singleton for Repository
single { Repository() }
// ViewModel scoped for the UI
viewModel { MyViewModel(get()) }
}
Explanation:
single { Repository() }
creates a singleton instance ofRepository
.viewModel { MyViewModel(get()) }
providesMyViewModel
and injectsRepository
into it.
Step 3: Configure the Application Class
You need to start Koin when your app launches. Update your Application
class:
import android.app.Application
import org.koin.android.ext.koin.androidContext
import org.koin.core.context.startKoin
class MyApp : Application() {
override fun onCreate() {
super.onCreate()
// Start Koin
startKoin {
androidContext(this@MyApp)
modules(appModule)
}
}
}