Resource
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
}
}Content copied to clipboard
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 visibleContent copied to clipboard
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