Android – Sealed Classes in Kotlin

Tram Ho

I. Introduction

Sealed Classes in Kotlin is a new concept that is not available in Java. Sealed Classes is an extension of traditional ENUM classes.

A sealed class allows you to represent constrained hierarchies in which an object can only be of one of the given types.

This means, we have a class with a specific number of subclasses. What we have is finally like an Enum. The difference is that in enum we only have one object per class, while with sealed classes we can have some objects of the same class. This difference helps to allow objects from a sealed class to hold the state.

II. Declaring Sealed classes

A sealed classes may have multiple subclasses, but all of them must be declared in the same file as the sealed sealed classes. For example:

The above code uses interface from view model to fragment

  • Loading: To know when to start and end an Api call to show or hide progress
  • CustomSignal: Use to send as Message or code
  • Failure: Use to fire an error

III. Use sealed classes

Now that we know how to create sealed classes, it’s time to use it. As I mentioned, I used the sealed classes above to communicate from view model to fragment

To understand the details of using sealed classes, two things need to be understood:

  • Where and how the data is updated
  • Where and how data is used

1. Where and how is the data updated?

In this case I updated the livedata sealed classes in the viewmodel before and after calling the api, as follows:

2. Where and how is data used?

Now we need to see how to use the data in the viewmodel:

IV. summary

Above is an introduction article about Sealed classes in Kotlin.

Thank you for reading.

ref: medium

Share the news now

Source : Viblo