Resource

sealed class Resource<T>

A sealed class that represents the result of a resource operation with loading, success, and error states.

This class is particularly useful for offline-first architectures where you want to show cached data while loading fresh data from the network. Each state can optionally include data, allowing you to display stale data while fetching updates.

States

  • Success: Operation completed successfully with data

  • Loading: Operation in progress, optionally with cached/stale data

  • Error: Operation failed with an error, optionally with cached/stale data

Usage Example

// In a Repository
fun getUsers(): Flow<Resource<List<User>>> = networkBoundResource(
query = { localDataSource.observeUsers() },
fetch = { networkDataSource.getUsers() },
saveFetchedResult = { users -> localDataSource.saveUsers(users) },
shouldFetch = { cachedUsers -> cachedUsers.isEmpty() }
)

// In a ViewModel (if not using UiState wrapper)
val users: StateFlow<Resource<List<User>>> = repository.getUsers()
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), Resource.Loading())

// In UI
when (val resource = usersState.value) {
is Resource.Loading -> {
// Show loading indicator
// Optionally show cached data: resource.data
}
is Resource.Success -> {
// Show fresh data: resource.data
}
is Resource.Error -> {
// Show error message: resource.error
// Optionally show stale data: resource.data
}
}

Offline-First Pattern

// Loading with cached data
Resource.Loading(cachedData) // Shows cached data while loading

// Error with cached data
Resource.Error(cachedData, exception) // Shows error but keeps cached data visible

Parameters

T

The type of data.

See also

For creating offline-first data flows

dev.atick.core.ui.utils.UiState

For the recommended state wrapper pattern

Inheritors

Types

Link copied to clipboard
class Error<T>(data: T? = null, error: Throwable) : Resource<T>

Represents an error state with optional cached data and error information.

Link copied to clipboard
class Loading<T>(data: T? = null) : Resource<T>

Represents a loading state with optional cached data.

Link copied to clipboard
class Success<T>(data: T) : Resource<T>

Represents a successful result with data.

Properties

Link copied to clipboard
val data: T?

The data result of the operation (can be null for initial loading states).

Link copied to clipboard

The error that occurred during the operation (only set in Error state).