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")
}
}

Parameters

initialValue

Starting value (automatically clamped to [min, max]).

min

Lower bound, inclusive. Default: Int.MIN_VALUE.

max

Upper bound, inclusive. Default: Int.MAX_VALUE.

step

The amount to add or subtract on each increment or decrement. Must be positive. Default: 1.

Constructors

Link copied to clipboard
constructor(initialValue: Int = 0, min: Int = Int.MIN_VALUE, max: Int = Int.MAX_VALUE, step: Int = 1)

Properties

Link copied to clipboard
val count: Int

The current counter value.

Link copied to clipboard
val max: Int
Link copied to clipboard
val min: Int
Link copied to clipboard
val state: StateFlow<Int>

The current counter value as a StateFlow.

Link copied to clipboard
val step: Int

Functions

Link copied to clipboard
fun decrement()

Decrements the counter by step, clamped to min.

Link copied to clipboard
fun increment()

Increments the counter by step, clamped to max.

Link copied to clipboard
fun reset()

Resets the counter to the original initialValue.

Link copied to clipboard
fun set(value: Int)

Sets the counter to value, clamped to [min, max].

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