KStateWithHistory

class KStateWithHistory<T>(defaultValue: T, capacity: Int = 10)(source)

Holds a value and a capped history of past values, supporting undo/redo.

Port of the useStateWithHistory and useUndoRedo React hooks.

val history = StateWithHistory("hello", capacity = 10)

history.set("world")
history.set("!")

history.back() // → "world"
history.forward() // → "!"

println(history.canUndo) // true
println(history.canRedo) // false

// Observe reactively:
history.state.collect { v -> println(v) }

Parameters

defaultValue

Initial value pushed into history.

capacity

Maximum number of history entries retained. Default: 10.

Constructors

Link copied to clipboard
constructor(defaultValue: T, capacity: Int = 10)

Properties

Link copied to clipboard

true when there is at least one step to redo.

Link copied to clipboard

true when there is at least one step to undo.

Link copied to clipboard

Index of the current entry within historySnapshot.

Link copied to clipboard

Snapshot of the history list (oldest → newest, up to capacity entries).

Link copied to clipboard
val state: StateFlow<T>

The current value as a StateFlow.

Link copied to clipboard
val value: T

The current value.

Functions

Link copied to clipboard
fun back()

Moves one step back in history. No-op if already at the oldest entry.

Link copied to clipboard
fun forward()

Moves one step forward in history. No-op if already at the newest entry.

Link copied to clipboard
fun go(index: Int)

Jumps to an arbitrary history index. No-op if out of bounds.

Link copied to clipboard
fun redo()

Alias for forward.

Link copied to clipboard
fun set(newValue: T)

Updates the value and records it in history. Any redo history ahead of the current pointer is discarded.

Link copied to clipboard
open override fun toString(): String
Link copied to clipboard
fun undo()

Alias for back.