Control & Timing

Rate-limit, pause, and schedule stream emissions.

debounce

Only publish after a quiet period. When values arrive rapidly, only the last one is emitted after the delay:

val search = StreamSource("")
val debounced = search.debounce(300)  // 300ms delay

// Typing rapidly: "h", "he", "hel", "hell", "hello"
// Only "hello" is published — 300ms after the last keystroke

cutoffWhen / cutoffWhenNot

Pause a stream based on a boolean predicate stream. While paused, the source is fully unsubscribed. When resumed, the current value is published immediately:

val source = StreamSource(1)
val paused = StreamSource(false)

val stream = source.cutoffWhen(paused)

// stream publishes values while paused() is false
source(2)  // published

paused(true)
source(3)  // NOT published — stream is cut off

paused(false)
// immediately publishes source's current value (3)

ticker

Emits a TickerFrame at regular intervals. Only runs while subscribed:

import io.peekandpoke.ultra.streams.ops.ticker

val tick = ticker(1000)  // every 1000ms

val unsub = tick.subscribeToStream { frame ->
    println("Tick #${frame.count}, delta: ${frame.deltaTime}ms")
}

// ... later
unsub()  // stops the ticker

Also accepts a Duration: ticker(1.seconds), or any FrameClock: ticker(clock), whose initial frame carries the time 0.0 and the next ones the clock's times. Times are in milliseconds, with fractions.

FrameClock

The clock a motion runs on: next(onFrame) calls back once, on the next frame, with the frame's time in milliseconds, and returns the way to cancel. FrameClock.default is the browser's animation frames on JS (FrameClock.animationFrames) and a 60 Hz FrameClock.ticker() elsewhere. A test passes its own clock and drives it frame by frame:

import io.peekandpoke.ultra.streams.ops.FrameClock

val handClock = FrameClock { onFrame ->
    pending = onFrame        // run it when the test says so
    ({ pending = null })     // cancel
}

On the JVM and native, FrameClock.ticker(context = ...) calls back on that context's threads: pick the one the source emits on, since streams are not thread-safe.

smooth

Smooths a Stream<Double?>: each new value is approached a step per frame, also while the source holds still, by one of the Smoothing laws. The default is exponential:

import io.peekandpoke.ultra.maths.Smoothing
import io.peekandpoke.ultra.streams.ops.smooth

// Keeps 90% of the way left per 10 ms
val needle = level.smooth(sharePer10Ms = 0.9)

// Any law: an analog needle that overshoots and settles
val analog = level.smooth(Smoothing.Spring(stiffness = 200.0, damping = 10.0), rest = 0.0, near = 0.001)
  • The first value after someone starts listening is taken as it is: a needle shown anew starts at its reading.
  • null, NaN and infinity pass at once as null; after a null the motion starts from rest.
  • A value on the way becomes the new goal; the motion keeps its speed.
  • Within near (in the value's units) it lands exactly on the value and stops asking for frames: no endless trickle of values.
  • The source is listened to only while someone listens; no frame is asked for while nothing moves.

The law can be a stream too, and change while the stream moves: the next step goes from the current position and speed by the new law, so a spring taking over swings on. A law of null passes values at once.

val law = StreamSource<Smoothing?>(Smoothing.Exponential(keepPer10Ms = 0.5))
val bulb = brightness.smooth(smoothing = law)

// A stutter: a new law, no restart of the motion
law(Smoothing.Spring(stiffness = 300.0, damping = 4.0))

quantize

Snaps every value to the nearest offset + k * size; the offset shifts the grid, not the value. null passes:

import io.peekandpoke.ultra.streams.ops.quantize

val stepped = level.smooth(sharePer10Ms = 0.9).quantize(size = 0.1)              // 0.0, 0.1, 0.2, ...
val shifted = level.quantize(size = 0.1, offset = 0.05)                          // 0.05, 0.15, ...

While a smoothed motion runs, quantize passes the same grid value on every frame; add .distinct() to publish only the changes.

mapAsync

Maps values asynchronously. The result stream is nullable — null until the first async operation completes:

And there it is — the one place where "always has a value" meets async reality. The value is null until the coroutine finishes. We're not going to pretend otherwise.
val userId = StreamSource("user-1")

val user = userId.mapAsync { id ->
    api.fetchUser(id)  // suspend function
}

// user() is null initially, then the fetched User object