Convert UiStates from data class to sealed interface
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
@qamarelsafadi Should I start working on this?
这是来自QQ邮箱的假期自动回复邮件。 您好,我最近正在休假中,无法亲自回复您的邮件。我将在假期结束后,尽快给您回复。