Skip to main content

Android ViewModel module

The module provides Container factory extensions on ViewModel for

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:

  1. 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.
  2. 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
)

...
}