ViewModelState

sealed class ViewModelState<T : Any>(source)

Screen state stored as JSON in the supplied SavedStateHandle. Call APIs on the main thread, using a main-thread scope. Restoration guarantees are those of the handle's owner. Keep payloads small and replace collections instead of mutating them in place.

Inheritors

Types

Link copied to clipboard
class Regular<T : Any>(name: String, serializer: KSerializer<T>, stateHandle: SavedStateHandle, scope: CoroutineScope, json: Json = Json, default: T? = null, workerDispatcher: CoroutineDispatcher = Dispatchers.Default) : ViewModelState<T>

Plain values from one-shot or continuous sources.

Link copied to clipboard
class Result<T : Any>(name: String, serializer: KSerializer<T>, stateHandle: SavedStateHandle, scope: CoroutineScope, json: Json = Json, default: T? = null, workerDispatcher: CoroutineDispatcher = Dispatchers.Default) : ViewModelState<T>

Persists payloads; loading and errors are transient. Restored non-null data starts as Success.

Properties

Link copied to clipboard
val data: StateFlow<T?>

Saved payload stream, independent of execution status.

Link copied to clipboard

Key owned by this state; its raw SavedStateHandle representation is a JSON string.

Link copied to clipboard
val scope: CoroutineScope

Scope controlling operations, usually viewModelScope.

Link copied to clipboard
val workerDispatcher: CoroutineDispatcher

Dispatcher for repository work, transformations and serialization.

Functions

Link copied to clipboard
fun cancel()

Stops the active operation without clearing state or completing its observers.

Link copied to clipboard
fun get(): T?

Reads the restored or latest saved payload.

Link copied to clipboard

Clears the payload without disconnecting observers.

Link copied to clipboard
fun <R> select(transform: (T?) -> R): StateFlow<R>

Synchronous projection for cheap work. Use selectAsync for expensive computations.

Link copied to clipboard
fun <R> selectAsync(initialValue: R, transform: suspend (T?) -> R): StateFlow<R>

Computes an expensive derived state asynchronously; reads reuse its last completed value.

Link copied to clipboard
open fun set(value: T?)

Synchronous write for small values. Throws on codec failure, preserving the prior state. Prefer setAsync for expensive payloads; this method runs on the calling thread.

open fun set(value: T?, distinct: Boolean)

Compatibility overload: skips encoding equal values when distinct is true.

Link copied to clipboard
fun setAsync(value: T?): Job

Prepares a detached saved snapshot on workerDispatcher, then commits on the owner scope. Replaces the active operation. Prefer this to synchronous set for expensive payloads. Plain failures propagate to the scope; result holders expose an Error with the old payload.