Kotlin Multiplatform Development stable Help

Common ViewModel

The Android ViewModel approach to building UI can be implemented in common code using Compose Multiplatform.

Adding the common ViewModel to your project

To use the multiplatform ViewModel implementation, add the following dependency to your commonMain source set:

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

Using ViewModel in common code

Compose Multiplatform implements the common ViewModelStoreOwner interface, so in general using the ViewModel class in common code is not much different from Android best practices.

Using the navigation example:

  1. Declare the ViewModel class:

    class OrderViewModel : ViewModel() { private val _uiState = MutableStateFlow(OrderUiState(pickupOptions = pickupOptions())) val uiState: StateFlow<OrderUiState> = _uiState.asStateFlow() // ... }
  2. Add the ViewModel to your composable function:

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

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.

Last modified: 31 May 2024