Android ViewModel module
The module provides Container factory extensions on Android's ViewModel for:
- Creating containers scoped with
ViewModelScope
to automatically cancel the
Container
whenever the
ViewModel
is cleared. - Saved state functionality via Jetpack's Saved State module for ViewModel to automatically save and restore the Container state on Activity or process death.
Including the module
implementation("org.orbit-mvi:orbit-viewmodel:<latest-version>")
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
In order to automatically save state on process death or when your Activity
is
destroyed there are two conditions:
- Your State can be put into an Android Bundle. Most commonly this will mean you need to implement the Parcelable interface on your state object. Using Kotlin's @Parcelize is recommended for ease of use.
- You need to pass in a
SavedStateHandle
to your
Container
factory function. The easiest way to do this is via
Koin's support.
This can be set up using Dagger as well but this could mean creating your own
custom equivalent of
androidx.lifecycle.SavedStateViewModelFactory
Usage with Koin:
// Declare the ViewModel with a saved state handle in your Koin module
val viewModelModule = module {
viewModel { (handle: SavedStateHandle) -> ExampleViewModel(handle) }
}
// Inject as a stateViewModel in your Activity or Fragment
private val viewModel by viewModel<ExampleViewModel>()
// Pass the SavedStateHandle to your ViewModel
class ExampleViewModel(savedStateHandle: SavedStateHandle) : ContainerHost<ExampleState, Nothing>, ViewModel() {
override val container = container<ExampleState, Nothing>(
ExampleState(),
savedStateHandle
)
...
}