Modeling UI State with Sealed Classes
Apply sealed classes to represent Loading, Success, and Error UI states.
Modeling UI State with Sealed Classes is a free Kotlin Academy lesson on CoddyKit. This is lesson 3 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Kotlin Academy learning path, and your progress syncs across the web and the CoddyKit app. The Kotlin Academy course includes 4 lessons in total.
The UI State Problem
The Classic Boolean Hell
// Fragile: isLoading=true AND hasError=true is invalid
var isLoading = false
var hasError = false
var data: List<Item>? = null
// 8 combinations, most of which are invalid!Sealed State: Only Valid States
sealed class UiState<out T>
object Loading : UiState<Nothing>()
data class Success<T>(val data: T) : UiState<T>()
data class Error(val message: String, val retryable: Boolean = true) : UiState<Nothing>()
object Empty : UiState<Nothing>()Rendering Based on State
fun render(state: UiState<List<Item>>) = when (state) {
Loading -> showProgressBar()
is Success -> showItems(state.data)
is Error -> showError(state.message, state.retryable)
Empty -> showEmptyView()
}ViewModel Emitting States
class ItemViewModel : ViewModel() {
private val _state = MutableStateFlow<UiState<List<Item>>>(Loading)
val state: StateFlow<UiState<List<Item>>> = _state
fun loadItems() = viewModelScope.launch {
_state.value = Loading
_state.value = try {
Success(repository.getItems())
} catch (e: Exception) {
Error(e.message ?: "Unknown error")
}
}
}Composing States with Content Inside
fun <T> loading(): UiState<T> = Loading
fun <T> success(data: T): UiState<T> = Success(data)
fun <T> error(msg: String): UiState<T> = Error(msg)Pagination State Example
sealed class PageState
object Idle : PageState()
object FirstLoad : PageState()
data class Content(val items: List<Item>, val hasMore: Boolean) : PageState()
data class LoadingMore(val items: List<Item>) : PageState()
data class Error(val items: List<Item>?, val msg: String) : PageState()Transforming State
fun <T, R> UiState<T>.mapData(transform: (T) -> R): UiState<R> = when (this) {
is Success -> Success(transform(data))
is Error -> this
Loading -> Loading
Empty -> Empty
}Testing with Sealed States
@Test
fun testLoadingState() {
viewModel.loadItems()
assertEquals(Loading, viewModel.state.value)
}
@Test
fun testSuccessState() {
viewModel.setData(listOf(item))
assert(viewModel.state.value is Success)
}Combined State vs Multiple Flows
// Fragile: two flows must stay in sync
val loading = MutableStateFlow(false)
val error = MutableStateFlow<String?>(null)
// Clean: one sealed state
val state = MutableStateFlow<UiState<List<Item>>>(Loading)Adding Metadata to States
data class Error(
val message: String,
val code: Int = 0,
val retryable: Boolean = true,
val timestamp: Long = System.currentTimeMillis()
) : UiState<Nothing>()Quick Check
Recap
Learn Kotlin with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 51
- Lessons
- 203
Frequently Asked Questions
Is the “Modeling UI State with Sealed Classes” lesson free?
Yes — any 3 lessons of the Kotlin Academy learning path, including “Modeling UI State with Sealed Classes”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Kotlin Academy course includes 4 lessons in total.
What will I learn in “Modeling UI State with Sealed Classes”?
Apply sealed classes to represent Loading, Success, and Error UI states. You practise Kotlin Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Kotlin Academy?
No prior experience is required. Kotlin Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.
How long does the “Modeling UI State with Sealed Classes” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Kotlin Academy lesson?
Yes. Every Kotlin Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- sealed class vs sealed interface: When to Use Each
- Exhaustive when with Sealed Hierarchies
- Modeling UI State with Sealed Classes
- Nesting and Combining Sealed Hierarchies