Skip to content

Modelling State in Kotlin

Published: at 03:20 PM

State in an app is any value that can change over time. All Android apps display state to the user. A few examples of state in Android apps:

Table of contents

Open Table of contents

Generel aspects of state

An app can be in one of the following states:

The app is not in initial state and not performing any operations.

The app is fetching data to show to the user.

The app has encounntered an error while fetching data.

The app has successesfully fetched data and can present it to the user.

Now we know what state is and what are the general aspects of state, let’s take a look at how we can model state:

Modeling state with sealed & data classes

By using a combination of sealed & data classes, we can easily model state:

sealed class FeaturedContentUiState {
    data object Initial : FeaturedContentUiState()
    data object Loading : FeaturedContentUiState()
    data object Error : FeaturedContentUiState()
    data class Success(
        val movies: List<Movie> = emptyList()
    ) : FeaturedContentUiState()
}

I have used this approach in my PocketMovies app which you can find here.

Modeling state with data class only

You can also model state using only data classes:

data class FeaturedContentState(
    val isLoading: Boolean = false,
    val error: Throwable? = null,
    val data: List<Movie> = emptyList()
)

You can further enhance state class by adding more properties and defining an empty state:

data class FeaturedContentState(
    val isLoading: Boolean = false,
    val error: Throwable? = null,
    val data: List<String> = emptyList()
) {
    val hasError: Boolean
        get() = error != null

    companion object {
        val Empty = FeaturedContentState()
    }
}