KC Blog

【Compose Multiplatform】Cross-Platform App with Android Context Implementation Using Koin

2 min read
CrossPlatform#CMP#Dependency Injection#Koin#Kotlin

Introduction

When developing Compose Multiplatform projects

we need to handle platform-specific issues

One problem we encounter is that

Android platform requires Context while iOS doesn't

This article will introduce how to

successfully solve this problem when using Koin for dependency injection

{% include table/compose-multiplatform-category.html %}

Implementation Methods

1. Using expect and actual Keywords
First

we need to use CMP's expect and actual keywords to provide different implementations for different platforms

First create the expect in commonMain

In this example, SettingDataStore needs context

and LearningViewModel needs SettingDataStore

so I created an expect platformModule variable

2. Android Platform Implementation
On the Android platform, we need to implement platformModule

where I expect dataStore needs to get a context:

3. iOS Platform Implementation
On the iOS platform, we don't need Context

so we can implement it directly

4. Initialize Koin
Initialize Koin at each platform's entry point:

Android

At the Android entry point, get the context

and insert it into the startKoin module list

iOS:

Usage

Using koinViewModel injected ViewModel in commonMain:

Or you can use get() in the module to help generate the instances you need

Conclusion

  • Using expect and actual keywords can handle platform differences
  • Koin provides DI support in Compose Multiplatform
  • Properly handling Context makes cross-platform code clearer and more maintainable
  • This method can be applied to other platform-specific dependency injection scenarios
  • In actual development, you can flexibly adjust DI strategies according to your own needs