SaveState<Value>
Represents the different states involved in saving data of type Value. Every state (except Idle) carries the current value, ensuring you always have access to the data being operated on.
Table of contents
States
Idle
Represents the idle state, before any save operation has been initiated.
val idleState = SaveState.Idle
Saving<Value>
Represents the saving state, indicating that data is currently being stored. Supports the invoke() operator.
val savingState = SaveState.Saving("value")
val value = savingState() // "value"
Saved<Value>
Represents the saved state of data. Supports the invoke() operator.
val savedState = SaveState.Saved("value")
val value = savedState() // "value"
Failure<Value>
Represents the failure state, containing the value and an exception.
val failureState = SaveState.Failure("value", RuntimeException())
State Checks
All state check functions use Kotlin contracts for smart casting.
isIdle()
SaveState.Idle.isIdle() // true
isSaving()
SaveState.Saving("value").isSaving() // true
isSaved()
SaveState.Saved("value").isSaved() // true
isFailure()
SaveState.Failure("value", RuntimeException()).isFailure() // true
Reactive Callbacks
onIdle
SaveState.Idle.onIdle { println("Idle") }
// Output: Idle
onSaving
SaveState.Saving("value").onSaving { value ->
println("Saving: $value")
}
// Output: Saving: value
onSaved
SaveState.Saved("value").onSaved { value ->
println("Saved: $value")
}
// Output: Saved: value
onFailure
SaveState.Failure("value", RuntimeException("error")).onFailure { value, throwable ->
println("Failed to save $value: ${throwable.message}")
}
// Output: Failed to save value: error
Exception Access
exceptionOrNull()
Returns the exception if Failure, or null otherwise.
SaveState.Failure("value", RuntimeException()).exceptionOrNull() // RuntimeException
SaveState.Saved("value").exceptionOrNull() // null
exceptionOrThrow()
Returns the exception if Failure, or throws IllegalStateException.
SaveState.Failure("value", RuntimeException()).exceptionOrThrow() // RuntimeException
SaveState.Saved("value").exceptionOrThrow() // throws IllegalStateException
Transformation
map
Maps the value of the state to a new value. Idle is passed through unchanged.
SaveState.Saving("value").map { it.length } // SaveState.Saving(5)
SaveState.Saved("value").map { it.length } // SaveState.Saved(5)
SaveState.Failure("value", RuntimeException()).map { it.length } // SaveState.Failure(5, ...)
fold
Folds the state into a single value by providing handlers for each state.
val state: SaveState<String> = SaveState.Saved("value")
val result = state.fold(
onIdle = { "Idle" },
onSaving = { value -> "Saving: $value" },
onSaved = { value -> "Saved: $value" },
onFailure = { value, error -> "Failed: ${error.message}" }
)
// result = "Saved: value"