0

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?

BArtWell
  • 4,176
  • 10
  • 63
  • 106
  • 1
    use `remember { ViewModel() }` - on Desktop there're no configuration changes, so `remember` would live through app lifecycle. – Phil Dukhov Mar 16 '23 at 08:32
  • @PhilDukhov In this case it's re-creating when we are getting back from another screen above. – BArtWell Mar 16 '23 at 10:04
  • 1
    that's true, but it should be handled by your navigation library, as view model lifecycle should be bind to screen lifecycle. Not sure if icerock has any setup for it - their main targets are mobile platforms after all – Phil Dukhov Mar 16 '23 at 11:46

0 Answers0