Member-only story

Integrating Koin Dependency Injection with Jetpack Compose in Android

Siva Nimmala
4 min readNov 28, 2024

Integrating Koin Dependency Injection with Jetpack Compose in Android
Koin Dependency Injection with Jetpack Compose

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 of Repository.
  • viewModel { MyViewModel(get()) } provides MyViewModel and injects Repository 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)
}
}
}

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Siva Nimmala
Siva Nimmala

Written by Siva Nimmala

Android developer seeking a challenging role to contribute to cutting-edge mobile projects. Proven track record of delivering high-quality applications.

No responses yet

Write a response