【Compose Multiplatform】Using Dependency Injection with Koin
In Compose Multiplatform projects
dependency injection is an important design pattern
Koin, as a lightweight DI framework
is very suitable for cross-platform development
This article will introduce how to use Koin
for dependency injection in Compose Multiplatform
目錄
- 【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
Add to your .toml file:
Add to your build.gradle.kts:
Next, we need to implement the specific DI content:
You can implement this based on your actual needs
For example, we might plan to use viewmodel, database, datastore, etc.
You can categorize according to your actual needs
to make your code more maintainable and manageable
If your implementation happens to need cross-platform
access
for example, accessing Context in Android
then dependency injection needs to be injected separately
Based on different platforms and requirements, we have multiple ways to initialize Koin:
in iOSMain:
in androidMain:
If your implementation happens to not need cross-platform
access
you can use the following method to inject directly in commonMain
For koin-compose version 1.2.0, you can use KoinApplication
to make your code more cohesive
Or you can also use the original startKoin
:
After that, you can directly use koinViewModel
to inject viewmodels
Or for some components, you can use get()
in the module to help you get instances
- Koin can be used in Compose Multiplatform
- With appropriate configuration, Koin can be used flexibly on different platforms
- Using Koin greatly simplifies dependency management in cross-platform projects
- Choose the appropriate initialization method based on project scale and complexity