Skip to main content

Android and Common ViewModel

The module provides Container factory extensions on Android's ViewModel for:

caution

Common ViewModel (Multiplatform) support added in Orbit v10.0.0.

Including the module

implementation("org.orbit-mvi:orbit-viewmodel:10.0.0")

Creating a container in a ViewModel

This module contains a Container factory extension function on ViewModel to facilitate creating a scoped container.

class ExampleViewModel : ContainerHost<ExampleState, Nothing>, ViewModel() {

override val container = container<ExampleState, Nothing>(ExampleState())

...
}

Saved state functionality with Kotlinx Serialization (Multiplatform)

To automatically save state on process death or UI destruction, two conditions must be met:

  1. For multiplatform, your state needs to be serializable.
  2. You must provide a SavedStateHandle to the Container factory function, along with the serializer for your state.
@Serializable
data class ExampleState(
...
)

// Pass the SavedStateHandle and serializer to your ViewModel
class ExampleViewModel(savedStateHandle: SavedStateHandle) : ContainerHost<ExampleState, Nothing>, ViewModel() {

override val container = container<ExampleState, Nothing>(
initialState = ExampleState(),
savedStateHandle = savedStateHandle,
serializer = ExampleState.serializer()
)

...
}

Saved state functionality with Parcelable (Android only)

To automatically save state on process death or Activity destruction, two conditions must be met:

  1. Your state needs to be Parcelable. Using Kotlin's @Parcelize is recommended for ease of use.
  2. You must provide a SavedStateHandle to the Container factory function.
@Parcelize
data class ExampleState(
...
) : Parcelable

// Pass the SavedStateHandle to your ViewModel
class ExampleViewModel(savedStateHandle: SavedStateHandle) : ContainerHost<ExampleState, Nothing>, ViewModel() {

override val container = container<ExampleState, Nothing>(
initialState = ExampleState(),
savedStateHandle = savedStateHandle
)

...
}

SavedStateHandle limitations

On Android, SavedStateHandle stores data in a Bundle, which has key limitations:

  • Not Reliable for Process Death: It survives configuration changes but may lose data if the app is killed. Use Room or DataStore for critical data.
  • Limited Data Size: Bundles have size constraints, and large data can cause performance issues or TransactionTooLargeException. Store only simple UI states.
  • Task Stack Dependency: Data is lost if the task stack is cleared (e.g. app force-closed or removed from recents).

Best Practices:

  • ✅ Use for small, UI-related state (e.g., IDs, enums).
  • ❌ Avoid storing large or complex data—use persistent storage instead.
  • 🔄 Understand it’s for transient UI state, not long-term persistence.