This tutorial walks you through setting up Koin for dependency injection in a Kotlin Multiplatform
(KMP) project using Compose. We’ll cover shared code, platform-specific configurations,
and best practices.
You may be interested in these articles as well:
1. Add Koin Dependencies
In your shared module’s , add Koin dependencies:
2. Define Your Koin Modules
Create a file (e.g., ) in your to define your modules.
I recommend this to be in the root package (e.g. ), so it’s easy to see which
dependencies are available to inject.
Some modules may be specific to Android or iOS. These should be included
in the for their respective platforms.
3. Platform specific Koin startup
For each platform, we’ll provide the actual body of the function
along with a helper function to initialize Koin.
Android
Let’s create a new file in .
Maintain the same package name as created in .
androidMain:
Now call it in your class.
Done for Android.
iOS
In , in a Kotlin file for iOS (e.g., ):
(Maintain the same package name as created in )
Now call it in your file:
Done.
4. Injecting Dependencies
- For classes: implement and use or .
- For Compose screens: use to get your view models.
- For Classes added in Koin modules: using constructor params.
Example in a Compose screen:
Example in a repository or utility:
5. Best Practices
- Use for shared instances, for new instances, and for Compose view models.
- Use for platform-specific implementations (e.g., file pickers, context).
6. Summary
- Add Koin dependencies to your shared and platform-specific source sets.
- Define modules in shared code, and use for platform-specific modules.
- Initialize Koin in your platform entry points ( for Android, a helper for iOS).
- Inject dependencies using Koin’s APIs in your repositories, view models, and Compose screens.