This is an example of how you can create a common ViewModel to share as much code as possible between platforms.
In this example, we are using the approach presented in the KaMPKit, introduced in the PR 238. This approach leverages the expect/actual feature from KMP to implement the base ViewModel class, providing the minimum requirements for an implementation.
On Android it delegates the implemetation to the AndroidX ViewModel. On iOS we have to implement the ViewModel and handle its lifecycle manually.
We also have a Wrapper class on iOS to handle coroutines and flow. We decided to call it CallbackViewModel
as all async calls from coroutines are converted to callbacks. It is responsible for hiding the suspend operator and creating flow adapters for a smooth integration on iOS.
Android | iOS |
---|---|
![]() |
![]() |
Base Classes:
- Expected ViewModel - Expect definition in the common code for a ViewModel implementation;
- Actual Android ViewModel - Actual implementation of the common class using the AndroidX ViewModel as base class;
- Actual iOS ViewModel - iOS implementation of the common class;
- CallbackViewModel - iOS wrapper for ViewModels;
- FlowAdapter - iOS wrapper for Flows;
Implementations:
- CounterViewModel - Common ViewModel that is shared between Android and iOS;
- CounterCallbackViewModel - iOS ViewModel wrapper;
- MainActivity - Usage example on Android;
- CounterModel - Usage example on iOS;