KCircularBuffer

class KCircularBuffer<T>(val capacity: Int, initialItems: List<T> = emptyList())(source)

A fixed-capacity ring buffer (Circular Buffer).

When the buffer is full, adding a new item silently drops the oldest entry. This implementation is ideal for bounded logs, recent-search history, rolling telemetry windows, or any scenario where you only need to keep the last N items.

The buffer state is exposed as a StateFlow, making it easy to observe changes in a reactive UI.

Example usage:

val log = KCircularBuffer<String>(capacity = 3)
log.add("a") // Buffer: [a]
log.add("b") // Buffer: [a, b]
log.add("c") // Buffer: [a, b, c]
log.add("d") // Buffer: [b, c, d] ← "a" is automatically dropped

println(log.toList()) // Prints: [b, c, d]
println(log.latest()) // Prints: "d"

// In a Composable:
val items by log.state.collectAsState()
LazyColumn {
items(items) { Text(it) }
}

Parameters

capacity

The maximum number of items the buffer can retain. Must be ≥ 1.

initialItems

Optional list of items to pre-populate the buffer with (ordered oldest to newest). If the list size exceeds capacity, only the last capacity items are kept.

Type Parameters

T

The type of elements held in this buffer.

Constructors

Link copied to clipboard
constructor(capacity: Int, initialItems: List<T> = emptyList())

Properties

Link copied to clipboard
Link copied to clipboard

true when the buffer contains no items.

Link copied to clipboard

true when the buffer is at full capacity.

Link copied to clipboard
val size: Int

Number of items currently in the buffer.

Link copied to clipboard
val state: StateFlow<List<T>>

Snapshot of all items as a StateFlow (oldest → newest). Emits on every structural change.

Functions

Link copied to clipboard
fun add(item: T)

Adds item to the buffer. If the buffer is full, the oldest item is removed first.

Link copied to clipboard
fun addAll(items: Iterable<T>)

Adds all items in order, dropping oldest entries as needed to stay within capacity.

Link copied to clipboard
fun clear()

Removes all items from the buffer.

Link copied to clipboard
fun latest(): T?

Returns the most recently added item, or null if empty.

Link copied to clipboard
fun oldest(): T?

Returns the oldest item currently in the buffer, or null if empty.

Link copied to clipboard
fun remove(item: T)

remove a single item from the buffer.

Link copied to clipboard
fun toList(): List<T>

Returns a snapshot list ordered oldest → newest.

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