Common ViewModel
Edit pageLast modified: 24 October 2024The Android ViewModel approach to building UI can be implemented in common code using Compose Multiplatform.
warning
Support for the common
ViewModel
in Compose Multiplatform is Experimental.
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.2")
}
// ...
}
}
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:
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() },
) {
// ...
}
tip
When running coroutines in a
ViewModel
, remember that theViewModel.viewModelScope
value is tied to theDispatchers.Main.immediate
value, which might be unavailable on desktop by default. To make ViewModel coroutines work correctly with Compose Multiplatform, add thekotlinx-coroutines-swing
dependency to your project. See theDispatchers.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.