Representing UIState with Sealed Classes

Arun Yogeshwaran
3 min readOct 12, 2021

--

Kotlin offers some cool features right out of its standard library and one such feature is Sealed classes. In this blog, we will see how it can be used to model classes that can be used to represent various UI states of a screen.

Let’s dive right into the topic

One of the main benefits of sealed classes is seen when it’s used with a when statement. It enables to verify that the statement covers all the possible cases and there is no need to add an else block to the statement.

This can be better explained with a use case along with MVVM pattern

Consider the following scenario — We have to let the user enter a password in an EditText field and make a server call to evaluate the password and show the result back in UI.

The following flow chart explains the same and the various UI states that can occur is highlighted in Green

So, these states — Loading, Success, Failure can be part of the sealed class that we are going to create.

The thing to be noted here is that along with the state, the ViewModel also has to pass in a message to the UI layer to show it back to the user in some of the states like Loading and Error.

Now, this sealed class can be wrapped by the LiveData object in the ViewModel and can be exposed to the UI layer for observing the changes

What otherwise could have been 3 LiveData objects each for representing three different states is reduced to a single LiveData object with the help of the Sealed class.

Now, the View class observing this LiveData must handle all the possible states of the UIState class. This makes sure that the View class doesn’t miss out on any of the edge cases.

The above code is readable and easy to understand as it clearly indicates the various states that the UI can encounter.

If one of the states is not handled, Android Studio immediately shows a warning like this

Why Not Enums?

You might be thinking that all these can be done with the help of Enum class too.

The sealed modifier makes it impossible to have another subclass of this class outside of the file — Which makes it easy to see all the subclasses of a sealed class in a single place.

Another advantage of sealed classes is that they can hold instance-specific data. Each item can be either a class or an object — Check how Success is just an object in the example above.

Since enums don’t offer the above features, sealed classes would be a better fit for this use case of representing UI states.

Thanks for your time!

--

--