kotlinandroid-jetpack-composeviewmodelkotlin-multiplatformcompose-desktop

Main dispatcher is missing on Compose Desktop


Trying to integrate Jetpack ViewModel into KMP project.

With the following configuration, desktop app cannot be compiled (error bellow).

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" }

Koin

viewModelOf(::MyViewModel)

MyViewModel.kt

class MyViewModel(useCase: MyUseCase): androidx.lifecycle.ViewModel() {
    val data = useCase()
          .stateIn(
              scope = viewModelScope,
              SharingStarted.Eagerly,
              initialValue = emptyList()
          )
    ...
}

Compile time exception

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'


Solution

  • To provide the Main dispatcher for Compose Desktop you can use org.jetbrains.kotlinx:kotlinx-coroutines-swing dependency from kotlinx.coroutines.

    For other platforms, see the list of available Coroutines for UI