Overview
Resource is a sealed class that represents the state of an operation. It provides a type-safe way to handle different states like success, error, and loading in your application.
Package: com.bsvillarraga.spaceflightnews.core.common
Source: Resource.kt:7
Type Parameter
The type of data that the resource contains
States
Success
Represents a successful operation.
data class Success<out T>(val data: T?) : Resource<T>()
The data returned by the successful operation. Can be null.
Example:
val result = Resource.Success(data = articlesList)
Error
Represents a failed operation.
data class Error<out T>(
val code: String?,
val msg: String,
val error: Throwable? = null
) : Resource<T>()
Optional error code identifying the type of error
Human-readable error message
Optional throwable for detailed error information
Example:
val result = Resource.Error(
code = "404",
msg = "Article not found",
error = exception
)
Loading
Represents an operation in progress.
data class Loading<out T>(val data: T? = null) : Resource<T>()
Optional cached or preliminary data that can be shown while loading
Example:
val result = Resource.Loading(data = cachedArticles)
Usage Example
when (resource) {
is Resource.Success -> {
// Handle success
resource.data?.let { data ->
updateUI(data)
}
}
is Resource.Error -> {
// Handle error
showError(resource.msg)
}
is Resource.Loading -> {
// Show loading indicator
showProgressBar()
resource.data?.let { cachedData ->
// Optionally show cached data while loading
updateUI(cachedData)
}
}
}