BArtWell
BArtWell

Reputation: 4044

How to load ViewModels in Kotlin Desktop?

I have an multiplatform application based on JetBrains Compose for Android and Desktop. In common module I have screens (as a Composable functions) with ViewModels inherited from dev.icerock.moko.mvvm.viewmodel.ViewModel:

import dev.icerock.moko.mvvm.viewmodel.ViewModel

class MyIpViewModel() : ViewModel() {

    // Some logic
}

Screen:

@Composable
fun MyScreen() {
    val viewModel = // How to load MyScreenViewModel() here?

    Column {
        // Screen content
    }
}

I need to load ViewModels inside screens. In Android it is possible to add dependency androidx.lifecycle:lifecycle-viewmodel-compose and then load ViewModels using ViewModelProvider. But how to use ViewModels in Koltin Desktop?

Upvotes: 0

Views: 2726

Answers (1)

Mahozad
Mahozad

Reputation: 24612

Compose Multiplatform 1.6.10 has added support for common ViewModel.

See the official docs.

kotlin {
    sourceSets {
        commonMain.dependencies {
            implementation("org.jetbrains.androidx.lifecycle:lifecycle-viewmodel-compose:2.8.0")

Also, make sure to add org.jetbrains.kotlinx:kotlinx-coroutines-swing dependency for your desktop source set.

@Composable
fun MyComposable(
    viewModel: MyViewModel = viewModel { MyViewModel() },
) {
    // ...
}

Upvotes: 0

Related Questions