New Way Handle State, Event With Sealed Classes in Android
Sometimes, we want to represent an Event, a State in Android. Such as handle action click item ViewHolder
in RecyclerView
, or return state when calling API
from the server (SUCCESS, FAIL, LOADING
)… We have a lot of solutions for this case, for example use interface
, abstract class
, or enum class
…
With interface
or abstract class
, it is cumbersome as well as not suitable for expansion. Enum class
is often used to represent a state, however, it can show multi values but only allow a single instance of each value and it cannot contain additional information for each type.
For example we want a return state when calling API from the server with retrofit
enum class StateApi {
LOADING,
SUCCESS,
ERROR
}
The downside here is that we cannot insert additional data into each StateApi
type.
Such as ERROR(val exeption: Exption), SUCCESS(val data: Data)
…
It’s great to be in Kotlin
, Sealed class
is the best solution 👌
Intro Sealed classes
“Sealed classes = abstract classes + enum++ classes”
Sealed classes are used for representing restricted class hierarchies, when a value can have one of the types from a limited set, but cannot have any other type
Can be defined Sealed classes
is an extension of enum classes
, and whereas a subclass of a sealed class can have multiple instances that can contain a state. Each instance of Sealed class
can contain its own data
To declare a sealed class
, we put the sealed modifier before the name of the class. A sealed class
can have subclasses (object, data class
…), but all of them must be declared in the same file as the sealed class itself
sealed class StateApi {
object Loading : StateApi()
data class Success(val data: String) : StateApi()
data class Error(val error: Exception) : StateApi()
}
The example above: Loading, Success, Error
is a instance of StateApi.
The special thing here is Success
is data class
contain params
is data: String
and Error
contain params
is an error: Exception
. So we can easily return states when request data from API.
A sealed class is abstract by itself, it cannot be instantiated directly and can have abstract members. Sealed classes are not allowed to have non-private constructors
Some use cases for Sealed classes
Handle state request API
Handle event action item ViewHolder
replace for interface class
Besides, we can use sealed classes for ViewHolder
type, the action of view in fragment
or activity
…
Hopefully, this article will help you to understand more about how to use sealed classes
in real situations.
Let me know your thoughts on this article.
Thanks!!! Happy Coding! 😇