Skip to content
tezvyn:

Handling API State with a Sealed Class Wrapper

Source: geeksforgeeks.orgMediumHow cards are made

Handling API State with a Sealed Class Wrapper

Treat API calls as states, not just data. A sealed class wrapper (Success, Error, Loading) models these states for your UI. Use this with Retrofit to show spinners or errors without crashing. The footgun: don't scatter try-catch blocks; centralize them.

Why it exists

Raw API calls can fail in many ways, from network issues to server errors. If not handled gracefully, this leads to app crashes or confusing blank screens. We need a consistent, reusable system to manage the entire lifecycle of a network request—loading, success, and failure—and communicate that status clearly to the UI.

The mental model

Think of an API response not as the data itself, but as a package that can be in one of three states: Loading (it's on its way), Success (it arrived with the data), or Error (it got lost or broken). A Kotlin Sealed Class is a perfect container for this, forcing you to handle all three possibilities explicitly in your code and preventing unexpected UI states.

How it works

You create a generic sealed class, often called Resource<T>, with three nested classes: Success<T>(val data: T), Error<T>(val message: String), and Loading<T>. In your repository layer, you create a single, reusable suspend function like safeApiCall. This function takes another function—the actual Retrofit call—as its argument. It wraps the execution in a try-catch block on a background dispatcher. Inside the try, it executes the call. If the Retrofit Response is successful, it returns Resource.Success with the data. If not, it parses the error body and returns Resource.Error. The catch block handles network exceptions like IOException or HttpException, also returning Resource.Error.

When to use it

This pattern is a staple in modern Android development using an MVVM architecture with Kotlin Coroutines and Retrofit. It's perfect for any feature that fetches data from a remote server and needs to update the UI based on the request's status. It makes your ViewModel's LiveData or StateFlow emissions clean, predictable, and easy for the UI to consume.

When not to use it

For extremely simple apps with only one or two non-critical API calls, this might feel like overkill. It's also less necessary for "fire-and-forget" API calls where you don't care about the response or need to update the UI, such as logging analytics events.

One canonical example

A repository fetches a list of articles. The ArticlesRepository uses a generic safeApiCall function to wrap its Retrofit service call. The ViewModel calls articlesRepository.getArticles(). This function returns a Flow<Resource<List<Article>>>. The UI collects this flow: when the emission is Resource.Loading, it shows a progress bar; when it's Resource.Success, it hides the progress bar and displays the articles; when it's Resource.Error, it shows a toast with the error message.

Interview question

What is the primary advantage of using a sealed class wrapper like Resource<T> for API responses?

  • a.It strictly enforces that all API responses must contain a data payload.
  • b.It eliminates the need for try-catch blocks in the repository layer.
  • c.It ensures all API calls are automatically retried upon failure.
  • d.It provides a structured way to manage and communicate loading, success, and error states to the UI.Correct
Why?

The sealed class wrapper explicitly models and communicates the Loading, Success, and Error states of an API call, enabling consistent UI updates. While it centralizes error handling, the underlying `safeApiCall` function still uses try-catch blocks.

Just read this? Test yourself on what you have been reading.

Read the original → geeksforgeeks.org

You just looked this up. Could you explain it out loud?

That is the part interviews actually test. Tezvyn takes questions like this one and gives you what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on android — each one lists the topics its interview covers.

See open roles