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:
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:
Add the ViewModel to your composable function:
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.