I am not able to understand how/when to use sealed classes in Android using Kotlin. I have read the docs but still I am getting confused about its structure and how to use it. It'd of great help if someone could help me understand this.
Sealed classes allow us to represent hierarchies in a more flexible way. It’s also more readable and is used for better state management. Child-classes of Sealed class, can be of any type, like: data class, object class, any regular class, or even another sealed class.
This is how we define a sealed class in Android using Kotlin:
sealed class UiState {
object Loading : UiState()
data class Success(val successMessage: String) : UiState()
data class Error(val error: Throwable?) : UiState()
}
Let’s understand this part of the code:
object Loading : UiState() : declared this as an object, as we don’t need to know anything else at this stage.
data class Success(val successMessage: String) : UiState() : declared as data class, as we need the message when we got Success state.
data class Error(val error: Throwable?) : declared this as data class, as we need the Throwable when we got Error state.
Notice how we have used object Loading : UiState(). We are using the same sealed class name as the return type of “Loading” object. This says, that the “Loading” object belongs to “UiState” sealed class.
This is same for Success and Error states as well.
We can then use this sealed class as the following:
fun observeUiStates(uiState: UiState) = when(uiState) {
UiState.Loading -> println("Loading...Please wait.")
is UiState.Success -> println(uiState.successMessage)
is UiState.Error -> println(uiState.errorMessage)
}
In this aforementioned block of code we are passing the UiState sealed class as a parameter to observeUiStates() method and then by using when we are checking which is the current state of the app and then we will be handling the states accordingly.
Here for the sake of this example, I am just printing the result in the console.
Sealed classes, best work with Model-View-Intent pattern in Android by using RxJava.
By using them, we will now be able to observe to the state changes.
Whenever there is a new state of the app, this observeUiStates() method will give us that specific state only.
To keep it simple for this specific example, I am calling this method from main(). See the code below:
fun main() {
observeUiStates(UiState.Loading)
observeUiStates(UiState.Success("The Ui has returned success state.”))
}
This will print the following in the console:
Loading...Please wait.
The Ui has returned success state.