ViewModel Compose Multiplatform and Koin¶
Koin integration with Kotlin Multiplatform ViewModel and Jetpack Compose Multiplatform.
Koin is the pragmatic Kotlin & Kotlin Multiplatform Dependency Injection framework. For more information check out the Koin documentation.
The kmp-viewmodel-koin-compose
artifact provides the integration of kmp-viewmodel-compose
and Koin
,
helps us to retrieve ViewModel
in @Composable
functions from the Koin DI container
without manually dependency injection.
1. Add dependency¶
- Add
mavenCentral()
torepositories
list inbuild.gradle.kts
/settings.gradle.kts
.
// settings.gradle.kts
dependencyResolutionManagement {
[...]
repositories {
mavenCentral()
[...]
}
}
- Add dependency to
build.gradle.kts
of your shared module.
// build.gradle.kts
kotlin {
sourceSets {
val commonMain by getting {
dependencies {
implementation("io.github.hoc081098:kmp-viewmodel-koin-compose:0.8.0")
// NOTE: You can add `koin-core` dependency to your project to specify the version of Koin.
// For more information check out the [Koin KMP documentation](https://insert-koin.io/docs/reference/koin-mp/kmp#gradle-dependencies).
implementation("io.insert-koin:koin-core:${koinVersion}")
}
}
}
}
Snapshots of the development version are available in Sonatype's snapshots repository.
// settings.gradle.kts
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.PREFER_PROJECT)
repositories {
maven(url = "https://s01.oss.sonatype.org/content/repositories/snapshots/")
[...]
}
}
// build.gradle.kts
dependencies {
implementation("io.github.hoc081098:kmp-viewmodel-koin-compose:0.7.2-SNAPSHOT")
}
2. Declare ViewModel
in a Koin Module using factory
or factoryOf
¶
import com.hoc081098.kmp.viewmodel.ViewModel
import org.koin.core.module.Module
import org.koin.core.module.dsl.factoryOf
import org.koin.dsl.module
class MyRepository
class MyViewModel(
val myRepository: MyRepository,
val savedStateHandle: SavedStateHandle,
val id: Int,
) : ViewModel() {
// ...
}
val myModule: Module = module {
factoryOf(::MyRepository)
factoryOf(::MyViewModel)
}
[!NOTE] Make sure to include your module definition in the Koin DI container, for example:
For more information check out the Start Koin documentation.startKoin { // others ... modules(myModule) }
3. Retrieve ViewModel
in @Composable
s function via koinKmpViewModel
function¶
import org.koin.core.parameter.parametersOf
import com.hoc081098.kmp.viewmodel.koin.compose.koinKmpViewModel
@Composable
fun MyScreen(
id: Int,
viewModel: MyViewModel = koinKmpViewModel(
key = "MyViewModel-$id",
parameters = { parametersOf(id) }
)
) {
// ...
}