Size of uiState Class for Fragments / Activities

88 Views Asked by At

Question

Do I understand correctly, that according to googles guide on app architecture the uiState of a fragment/activity is commonly described by only ONE class (see picture below)?

For me as a beginner to programming it looks like the NewsUiState is a combination between the representation of the data (NewItemUiState) and the screen related things (e.g. isSignedIn).

But on complex UIs the uiState class must be easily 100's of properties long or what am I missing?

enter image description here

1

There are 1 best solutions below

2
ΓDΛ On

You can create more than one State data class.

Sample UseCase

sealed class UiState {
    data class Success(val data: Data) : UiState()
    data class Error(val error: Throwable) : UiState()
    object Loading : UiState()
}

How to Handle

fun handleUiState(uiState: UiState) {
    when (uiState) {
        is UiState.Success -> displayData(uiState.data)
        is UiState.Error -> displayError(uiState.error)
        UiState.Loading -> displayLoadingIndicator()
    }
}

Other Sample

sealed class UiState {
    data class Success(val data: Data) : UiState()
    data class Error(val error: Throwable) : UiState()
    object Loading : UiState()
    data class Validation(val errors: Map<String, String>) : UiState()
    data class Completed(val message: String) : UiState()
    object Init : UiState()
    object Empty : UiState()
}

The important thing here is to be able to break down the states related to the relevant screen. You can write your own uiStates for each component on the screen. This is good practice. It can be combined with Sealed class. You can stream data with a single stateflow or sharedflow.