architecture-samples icon indicating copy to clipboard operation
architecture-samples copied to clipboard

Convert UiStates from data class to sealed interface

Open qamarelsafadi opened this issue 2 years ago • 3 comments

qamarelsafadi avatar Jun 18 '23 13:06 qamarelsafadi

Here's how to convert UiStates from a data class to a sealed interface, which is a more idiomatic and type-safe way to model UI state in Kotlin — especially in Jetpack Compose or MVI architectures.

Why Use a sealed interface Instead of data class Encourages exhaustive when expressions (compiler checks all states).

Better separates UI states like Loading, Success, Error, Empty, etc.

Prevents illegal state combinations (unlike data classes with nullable fields).

Example: Convert UiState from data class to sealed interface Original (not recommended):

data class UiState<T>( val isLoading: Boolean = false, val data: T? = null, val error: String? = null ) Refactored (sealed interface version):

sealed interface UiState<out T> { object Loading : UiState<Nothing> data class Success<T>(val data: T) : UiState<T> data class Error(val message: String) : UiState<Nothing> object Empty : UiState<Nothing> } How to Use It ViewModel: val uiState = MutableStateFlow<UiState<List<Item>>>(UiState.Loading)

fun loadItems() { viewModelScope.launch { try { val items = repository.getItems() uiState.value = if (items.isEmpty()) UiState.Empty else UiState.Success(items) } catch (e: Exception) { uiState.value = UiState.Error(e.message ?: "Unknown error") } } } UI (Jetpack Compose):

when (val state = uiState.collectAsState().value) { is UiState.Loading -> LoadingScreen() is UiState.Success -> ItemList(items = state.data) is UiState.Error -> ErrorScreen(message = state.message) is UiState.Empty -> EmptyScreen() } Benefits Easier to test and maintain

More predictable and type-safe

Cleaner when statements in UI logic

VaradGupta23 avatar Jul 15 '25 13:07 VaradGupta23

@qamarelsafadi Should I start working on this?

Rajnish23 avatar Sep 27 '25 05:09 Rajnish23

这是来自QQ邮箱的假期自动回复邮件。   您好,我最近正在休假中,无法亲自回复您的邮件。我将在假期结束后,尽快给您回复。

thewyp avatar Sep 27 '25 05:09 thewyp