When an API call fails, showing a blank screen or crashing the app ruins the user experience. Here’s a clean way to manage those failures in MVVM using Kotlin.

What Challenges is facing in Android MVVM Architecture

If an API call fails because of network issues or server problems, many apps either crash or show a blank screen. How do you make sure users still see something useful?

Solution

Use a sealed class like Resource to handle different outcomes: Success, Error, and Loading. Then connect it with LiveData or StateFlow in your ViewModel to update the UI based on each case.

kotlin
// 1. Define the Resource wrapper
sealed class Resource<T> { data class Success<T>(val data: T): Resource<T>() data class Error<T>(val message: String): Resource<T>() class Loading<T>: Resource<T>()
}
// 2. Repository method
suspend fun getData(): Resource<User> = try { val response = api.getUser() Resource.Success(response)
} catch (e: Exception) { Resource.Error(e.localizedMessage ?: "Unknown Error")
}
// 3. ViewModel usage
val user = MutableLiveData<Resource<User>>()
fun fetchUser() = viewModelScope.launch { user.value = Resource.Loading() user.value = repository.getData()
}

Conclusion

Handling API failures properly isn’t optional. It’s basic hygiene for a smooth user experience. If you’re building serious apps or planning to hire Android developer talent, wrapping your responses in a Resource class helps keep your code cleaner and your UI more responsive to real-world issues.