尝试将 Jetpack ViewModel 集成到 KMP 项目中。
使用以下配置,桌面应用程序无法编译(错误如下)。
libs.versions.toml
androidxLifecycle = "2.8.0"
koin-compose = "1.2.0-Beta4"
navigation-compose = "2.8.0-alpha02"
androidx-lifecycle-viewmodel = { module = "androidx.lifecycle:lifecycle-viewmodel", version.ref = "androidxLifecycle" }
koin-compose-viewmodel = { module = "io.insert-koin:koin-compose-viewmodel", version.ref = "koin-compose" }
navigation-compose = { module = "org.jetbrains.androidx.navigation:navigation-compose", version.ref = "navigation-compose" }
科因
viewModelOf(::MyViewModel)
MyViewModel.kt
class MyViewModel(useCase: MyUseCase): androidx.lifecycle.ViewModel() {
val data = useCase()
.stateIn(
scope = viewModelScope,
SharingStarted.Eagerly,
initialValue = emptyList()
)
...
}
编译时异常
Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Module with the Main dispatcher is missing. Add dependency providing the Main dispatcher, e.g. 'kotlinx-coroutines-android' and ensure it has the same version as 'kotlinx-coroutines-core'
要为 Compose Desktop 提供主调度程序,您可以使用
org.jetbrains.kotlinx:kotlinx-coroutines-swing
中的 kotlinx.coroutines 依赖项。
对于其他平台,请参阅可用的UI 协程列表