Integrating Koin with Jetpack Compose

In our previous blog, we introduced Koin and set up a simple "Hello Koin" example to demonstrate dependency injection. Now, let’s take it a step further and explore how to integrate Koin with Jetpack Compose. This guide will help you leverage Koin to manage dependencies seamlessly in a modern Compose-based Android application.

Why Use Koin with Jetpack Compose?

Jetpack Compose is Android’s modern UI toolkit, and Koin’s Kotlin-first approach makes it an ideal match. Together, they provide:

  • Simplified dependency management: Koin handles dependencies, freeing you from manual instantiation.

  • Cleaner code: Compose’s declarative UI and Koin’s DSL complement each other for concise, readable code.

  • Scalability: Easy to manage dependencies across a growing application.

Setting Up Koin for Jetpack Compose

Step 1: Add Dependencies

Add the following dependencies to your build.gradle file:

implementation "io.insert-koin:koin-android:3.x.x"
implementation "io.insert-koin:koin-androidx-compose:3.x.x"

Replace 3.x.x with the latest version of Koin.

Step 2: Define Your Koin Modules

Let’s create a module for our Compose-based app. Assume we have a GreetingService to provide messages:

class GreetingService {
    fun getGreeting() = "Hello from Koin!"
}

val appModule = module {
    single { GreetingService() }
}

Step 3: Initialize Koin

Initialize Koin in your Application class:

import android.app.Application
import org.koin.core.context.startKoin

class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()

        startKoin {
            modules(appModule)
        }
    }
}

Declare the Application class in your AndroidManifest.xml file:

<application
    android:name=".MyApplication"
    ...>
</application>

Step 4: Inject Dependencies in Compose

Koin provides seamless integration with Compose using the koinComponent() and get() functions.

Here’s an example:

Create a Composable Function

import androidx.compose.runtime.Composable
import androidx.compose.material3.Text
import org.koin.androidx.compose.koinInject

@Composable
fun GreetingScreen() {
    val greetingService: GreetingService = koinInject()
    Text(text = greetingService.getGreeting())
}

In this example:

  • koinInject() retrieves the GreetingService instance from Koin.

  • The GreetingService is then used to display a greeting message.

Step 5: Set Up Your Compose UI

In your MainActivity, set the Compose content:

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material3.MaterialTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MaterialTheme {
                GreetingScreen()
            }
        }
    }
}

Running the App

When you run the app, the GreetingScreen will display the text: Hello from Koin!.

Exploring Advanced Features

Koin offers additional features for Compose integration, such as:

Using ViewModel with Compose

Koin’s viewModel() delegate simplifies ViewModel injection in Compose. Here’s an example:

Define a ViewModel

import androidx.lifecycle.ViewModel

class GreetingViewModel(private val greetingService: GreetingService) : ViewModel() {
    fun getGreetingMessage() = greetingService.getGreeting()
}

val viewModelModule = module {
    viewModel { GreetingViewModel(get()) }
}

Use the ViewModel in Compose

import androidx.compose.runtime.Composable
import org.koin.androidx.compose.koinViewModel

@Composable
fun GreetingScreen(viewModel: GreetingViewModel = koinViewModel()) {
    Text(text = viewModel.getGreetingMessage())
}

Passing Parameters

Koin supports parameter injection for more dynamic behavior. For instance:

val appModule = module {
    factory { (name: String) -> GreetingService(name) }
}

@Composable
fun GreetingScreen() {
    val greetingService: GreetingService = get { parametersOf("Compose") }
    Text(text = greetingService.getGreeting())
}

Akshay Nandwana
Founder AndroidEngineers

You can connect with me on:


Book 1:1 Session here
Click Here

Join our upcoming classes
https://www.androidengineers.in/courses

Love from our past students

Excellent list of questions really helped me to coverup all the topics before interview.

Saiteja Janjirala

10th Oct, 2024

I had an exceptional experience with the 1:1 mentorship session. Akshay was incredibly friendly and provided invaluable guidance on focusing on long-term goals. They also gave great interview tips, including a thorough resume review. Additionally, the discussion on Data Structures and Algorithms (DSA) was insightful and practical. Highly recommended for anyone looking to advance their career!

Nayab khan

11th Sep, 2024

Cleared my major points for what I am missing in the resume and also suggested what I can work on for further growth in the career.

Ketan Chaurasiya

7th Aug, 2024

What impressed me most was his personalized approach and practical tips that I could immediately apply. Akshay’s guidance not only improved my technical skills but also boosted my confidence in navigating my career path. His insights and encouragement have been a game-changer for me. I highly recommend Akshay’s mentorship to anyone looking to advance their Android development career.

Hardik Kubavat

5th Aug, 2024

2025© Made with   by Android Engineers.