【Compose Multiplatform】Cross-Platform App with Android Context Implementation Using Koin
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
目錄
- 【Compose Multiplatform】專案轉移探討與開發指南
- 【Compose Multiplatform】手機使用依賴注入Koin
- 【Compose Multiplatform 】跨平台App但Android需要context作法並搭配Koin
- 【Compose Multiplatform】手機本地持久化儲存DataStore實作
- 【Compose Multiplatform】手機資料庫SqlDelight實作
- 【Compose Multiplatform】CMP中使用ROOM開發資料庫 - [KSP2] Annotation value is missing in nested annotations
- 【Compose Multiplatform】CMP專案中導入CocoaPods及無CocoaPods情況下使用IOS Swift/Obj-C
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
On the Android platform, we need to implement platformModule
where I expect dataStore needs to get a context:
On the iOS platform, we don’t need Context
so we can implement it directly
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:
Using koinViewModel injected ViewModel in commonMain:
Or you can use get()
in the module to help generate the instances you need
- 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