Compose - View Model

  • ViewModel serves as a bridge, establishing a clear contract between your shared business logic and your UI components.

    Introduction

    ViewModel helps ensure data consistency across platforms, while enabling UIs to be customized for each platform’s distinct appearance. You can continue developing your UI with Compose on Android and SwiftUI on iOS.

    Read more about benefits of using ViewModel and all the features in the primary documentation for ViewModel.

    You can see the implementation in practice in our official sample (Only Android)

    Navigation example

    Project

    module.yaml

    To set up the KMP ViewModel in your project, define the dependency:

    androidx.lifecycle:lifecycle-viewmodel

    Declare the ViewModel class:

    import androidx.lifecycle.ViewModel
    import androidx.lifecycle.viewmodel.compose.viewModel
    class OrderViewModel : ViewModel() {
    private val _uiState = MutableStateFlow(OrderUiState(pickupOptions = pickupOptions()))
    val uiState: StateFlow<OrderUiState> = _uiState.asStateFlow()
    // ...
    }

    Add the ViewModel to your composable function:

    @Composable
    fun CupcakeApp(
    viewModel: OrderViewModel = viewModel { OrderViewModel() },
    ) {
    // ...
    }

    When running coroutines in a ViewModel, remember that the ViewModel.viewModelScope value is tied to the Dispatchers.Main.immediate value, which might be unavailable on desktop by default. To make ViewModel coroutines work correctly with Compose Multiplatform, add the kotlinx-coroutines-swing dependency to your project. See the Dispatchers.Main documentation for details.

    On non-JVM platforms, objects cannot be instantiated using type reflection. So in common code you cannot call the viewModel() function without parameters: every time a ViewModel instance is created, you need to provide at least an initializer as an argument.

    If only an initializer is provided, the library creates a default factory under the hood. But you can implement your own factories and call more explicit versions of the common viewModel(...) function, just like with Jetpack Compose.

    Pending