Response

sealed class Response<out T>

A generic class that holds a value with its loading status. Can be used to represent any operation that can be in one of the following states: Loading, Success, Error.

fun example() { // With data val responseWithData: Response = Response.Success("Hello")

// Empty success
val emptyResponse: Response = Response.SuccessEmpty
// Or using convenience constructor
val anotherEmptyResponse: Response = Response.success()

// Handling all cases
when (response) {
    is Response.Success -> println("Success with data: ${response.data}")
    is Response.SuccessEmpty -> println("Success with no data")
    is Response.Error -> println("Error: ${response.exception.message}")
    is Response.Loading -> println("Loading...")
}

// Using handlers
response
    .onSuccess { data -> println("Success: $data") }
    .onSuccessEmpty { println("Success with no data") }
    .onError { error -> println("Error: ${error.message}") }
    .onLoading { println("Loading...") }

}

Inheritors

Types

Link copied to clipboard
data class Error(val exception: Throwable) : Response<Nothing>

Represents a failed response containing an exception.

Link copied to clipboard
data object Loading : Response<Nothing>

Represents a loading state while an operation is in progress.

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

Represents a successful response containing data.

Link copied to clipboard
data object SuccessEmpty : Response<Nothing>

Represents a successful response with no data. Use this when an operation completes successfully but doesn't return any data.

Properties

Link copied to clipboard

Returns true if this response represents an error state.

Link copied to clipboard

Returns true if this response represents a loading state.

Link copied to clipboard

Returns true if this response represents a successful state (either Success or SuccessEmpty).

Functions

Link copied to clipboard
fun getOrDefault(defaultValue: T): T

Returns the data if this is a Success response, or the provided default value otherwise.

Link copied to clipboard
fun getOrNull(): T?

Returns the data if this is a Success response, or null otherwise.

Link copied to clipboard
inline fun <T, R> Response<T>.map(transform: (T) -> R): Response<R>

Transforms the data in this response using the provided transform function.

Link copied to clipboard
fun onError(action: (Throwable) -> Unit): Response<T>

Executes the given action if this is an Error response.

Link copied to clipboard
fun onLoading(action: () -> Unit): Response<T>

Executes the given action if this is a Loading response.

Link copied to clipboard
suspend fun onSuccess(action: suspend (T) -> Unit): Response<T>

Executes the given action if this is a Success response.

Link copied to clipboard
suspend fun onSuccessEmpty(action: suspend () -> Unit): Response<T>

Executes the given action if this is a SuccessEmpty response.