KCounter
class KCounter(initialValue: Int = 0, val min: Int = Int.MIN_VALUE, val max: Int = Int.MAX_VALUE, val step: Int = 1)(source)
A reactive mutable counter with optional min/max bounds and a configurable step.
This utility is a Kotlin port of common reactive counter hooks (like useCounter). It encapsulates the logic for incrementing, decrementing, and clamping values, while exposing the current count through a StateFlow.
Example usage:
val counter = KCounter(initialValue = 0, min = 0, max = 10, step = 2)
counter.increment() // count becomes 2
counter.decrement() // count becomes 0
counter.set(7) // count becomes 7
counter.increment() // count becomes 9
counter.increment() // count becomes 10 (clamped to max)
counter.reset() // count returns to 0
// Reactively observing in a ViewModel or Composable:
viewModelScope.launch {
counter.state.collect { value ->
println("Current count: $value")
}
}Content copied to clipboard
Parameters
min
Lower bound, inclusive. Default: Int.MIN_VALUE.
max
Upper bound, inclusive. Default: Int.MAX_VALUE.