【Compose Multiplatform】Cross-Platform App with Android Context Implementation Using Koin
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
Implementation Methods
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
where I expect dataStore needs to get a context:
so we can implement it directly
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