viewing-state-kmp

A Kotlin Multiplatform library for managing common UI state transitions.

Get Started View on GitHub


Overview

The viewing-state-kmp package provides sealed classes to handle common view state transitions in Kotlin Multiplatform projects:

State Class States Use Case
LoadState Idle, Loading, Loaded, Failure Fetching data from a remote source
SaveState Idle, Saving, Saved, Failure Persisting data to a remote source
MutationState Idle, Mutating, Mutated, Failure Editing data with original/updated tracking
ResourceState Idle, Loading, Loaded, LoadFailure, Saving, Saved, SaveFailure Combined load + save lifecycle

Why

Using these state classes simplifies managing common UI states. They centralize state logic in your ViewModel, making your Composable functions cleaner and focused solely on displaying the UI based on the current state.

This leads to more predictable and maintainable code by clearly defining and handling different stages of data presentation.

Platforms

  • Android (JVM 17, minSdk 28, compileSdk 35)
  • iOS Arm64
  • iOS Simulator Arm64

Quick Example

class MyViewModel : ViewModel() {
    private val _state = MutableStateFlow<LoadState<MyData>>(LoadState.Idle)
    val state: StateFlow<LoadState<MyData>> = _state.asStateFlow()

    fun fetchData() {
        viewModelScope.launch {
            _state.value = LoadState.Loading

            try {
                val result = repository.fetchData()
                _state.value = LoadState.Loaded(result)
            } catch (exception: Exception) {
                _state.value = LoadState.Failure(exception)
            }
        }
    }
}
@Composable
fun MyScreen(viewModel: MyViewModel = viewModel()) {
    val state by viewModel.state.collectAsState()

    when (state) {
        is LoadState.Idle -> Text("Click to load data.")
        is LoadState.Loading -> CircularProgressIndicator()
        is LoadState.Loaded -> Text("Data: ${state.valueOrThrow()}")
        is LoadState.Failure -> Text("Error: ${state.exceptionOrThrow().message}")
    }
}

This site uses Just the Docs, a documentation theme for Jekyll.