Dealing with Multiple APIs via Retrofit? Learn How to use Sealed Classes Effectively

Learn how to utilize the power of Sealed Classes & Generics to deal with different API responses.

“How to use Sealed Classes Effectively” by Bhavna Thacker

While developing a real world Android App from scratch, you often face this situation.

Week 1: Set up Project, implement Splash screen

Week 2: Login/Registration Screens (maybe 2 APIs integration)

Week 3: Home Screen — to Display List of XYZ and Detail Screen (one or more APIs integration)

Week 4: New features — More APIs again :(

This list grows as weeks pass, and for API integration, you already have a friend called Retrofit. But the beauty of APIs is that, each API will return a different Response :)

So, you wonder if there was a way to create a Generic Structure for API response.

Basically there are two things that happen.

You either get Success OR Error from API.

If success, the data could vary (It could be user, list of books, a book etc.)

If error, you need to know what went wrong (error message)

Here comes the Power of Sealed Classes and Generics.

Sealed Classes with Generics

Because, data could vary — You define data as Generic type (“T”) and as there are two possibilities of ResponseSuccess and Error, you can use Sealed Class to wrap this possibilities.

So, first start with something like this:

However, the above classes hold no state (you need to add data & message) and also type of data could vary with each API, making it generic. When it is Success, you surely get the data. When it is Error, you may get data or message but both of which are optional. With this in mind, modify above Sealed class definition to below:

With the above Template for API Response, let’s see how you apply this to a Book Reader App.

For an API which returns list of books, your app may have classes like this:

Call to getAllBooks returns — Books whereas call to getBookInfo returns Book, so the code in Repository class could look like below:

And your ViewModel may look like below, handling API response and updating the states:

If you are using Jetpack Compose for UI, your composable would depend on States list & isLoading to update the UI like below:

Congratulations! Now you are all set to handle any number of APIs, following a clean Architecture and also structured approach while dealing with API responses.

If you enjoyed reading above and found it useful, please leave a Clap, that motivates me to write more about what I just learnt :)



Android GDE. Youtuber — LearnAndroid. Senior Android Engineer @MEGA. FPE @raywenderlich.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store

Android GDE. Youtuber — LearnAndroid. Senior Android Engineer @MEGA. FPE @raywenderlich.