Skip to main content

Async work & timers

Terminal apps still fetch data, read files, poll services, and animate. glyphora keeps those operations predictable with one rule: do slow work off-thread; mutate UI signals on the render thread.

The Async helpers enforce that handoff for you.

Model loading explicitly​

A small state enum produces a clearer UI than parallel loading, error, and value flags:

private enum LoadState[+A]:
case Idle
case Loading
case Ready(value: A)
case Failed(message: String)

private val users = Signal[LoadState[Vector[User]]](LoadState.Idle)

Render each state in one place:

def usersView(using ReactiveScope, Theme): Element = users.get match
case LoadState.Idle => text("Press r to load users.").dim
case LoadState.Loading => spinner("loading…")
case LoadState.Ready(values) => list(values.map(_.name), userList)
case LoadState.Failed(message) => text(s"Load failed: $message").fg(Color.Red)

Run blocking work safely​

Async.runCatching executes admitted work on a daemon worker and delivers its result back on the captured render thread while that owner remains live:

private def reload(): Unit =
users.set(LoadState.Loading)
Async.runCatching(api.fetchUsers()) {
case Right(value) => users.set(LoadState.Ready(value))
case Left(error) => users.set(LoadState.Failed(error.getMessage))
}

Because the callback is already on the render thread, setting users is safe and automatically schedules the next render.

Use Async.run when your API already models errors in its result:

Async.run(api.fetchReport()) { result =>
report.set(result)
}

If the work itself throws, Async.run hands the throwable back to the render loop that armed the call. The runner absorbs it the way it absorbs any failing queued body — the app keeps running — and reports it when the app exits, as RunnerError.QueuedTask carrying the count and the stack traces. Take reporting over by putting an AsyncErrorHandler in scope:

given AsyncErrorHandler = AsyncErrorHandler.onRenderThread(error => failure.set(Some(error.getMessage)))

onRenderThread and toRenderThread() can be long-lived givens: Async.run binds their destination anew for each invocation, on the thread that arms it. Results and errors stay with that invocation's runner, even when two runners share the policy. A late delivery to a stopped owner is dropped, not rerouted to a surviving runner. Start the call from onStart, a handler, or another owner-thread callback.

Direct policy.handle(error) calls outside Async.run do not get this per-invocation binding: toRenderThread() uses the loop captured when the policy was constructed, while onRenderThread uses ordinary RenderThread.runLater routing at the call. Custom worker-side handlers, ignore, and rethrow keep their own behavior.

AsyncErrorHandler.rethrow throws on the worker thread instead. Escaping failures, including exceptions thrown by a custom worker-side error handler, reach that thread's uncaught-exception handler; they are not hidden in discarded futures. Only exceptions from the worker's work body go to onError. Dispatch failures—for example, a custom backend throwing from its wakeup—escape to the worker's uncaught handler instead. A result already queued before wakeup failed remains accepted. The same holds on the timer path: a repeating timer whose wake throws reports the throwable to the timer thread's uncaught-exception handler and keeps firing, instead of ending silently inside its ScheduledFuture. Avoid it in a terminal app: the JVM prints the stack trace to standard error, which is the tty the UI is drawn on, so the trace lands on top of the alternate screen and the frame diff never repaints over it.

Bounded admission and overload​

The shared worker pool uses max(2, availableProcessors) threads and admits 256 waiting submissions. Active render owners admit 1024 outstanding callbacks or reserved async/timer deliveries; the detached queue admits 256. Submission never waits for room or executes worker code on the caller. At capacity, Async.run, runCatching, timers, scoped task submission and off-thread render dispatch throw java.util.concurrent.RejectedExecutionException synchronously. This is admission failure, not a work failure passed to onError or an onDone(Left(...)) result.

Accepted async work reserves delivery capacity before starting, including its built-in render-thread error report. Overload does not evict previously accepted continuations. Retired owners still discard late delivery rather than rerouting it. Catch admission failure where starting work is optional, keep request loads single-flight where suitable, and retry only when capacity is available—not in an immediate retry loop.

Each repeating timer holds one reservation until cancelled. Ticks while its callback is pending or running coalesce into that delivery rather than accumulating for replay. This bounds timer backlog, not callback duration, and does not make overlapping HTTP loads single-flight. The bounds are per owner, not a global cap on runner instances. An unscoped timer that was never cancelled retires itself on its first firing after its owner has closed — the body never runs again and the scheduler entry is removed — but cancelling it in onStop is still the right habit: the body may hold resources of its own, and cancellation frees the reservation and the entry at once rather than one interval later.

Schedule one-shot and repeating work​

import scala.concurrent.duration.*

val dismiss: Cancelable = Async.after(2.seconds) {
notice.set(None)
}

val poller: Cancelable = Async.every(10.seconds) {
reload()
}

// Stop work when the owning screen closes.
poller.cancel()

Both callbacks run on the render thread. Returned Cancelable handles make lifecycle ownership explicit and prevent a screen that no longer exists from continuing to update app state. cancel() also discards callbacks already queued for delivery but not yet started. It is thread-safe and idempotent; a callback that has already started is allowed to finish without interruption. Cancelled scheduled entries are removed immediately rather than retained until their original deadlines.

Optional owner-scoped tasks​

Async.scope() creates a io.worxbend.tui.runtime.TaskScope on the current registered runner. Create it from onStart or a screen's onEnter, not from a field initializer. It shares the existing daemon worker pool and scheduler.

// Called on the owner, e.g. from onEnter:
val tasks = Async.scope()
val load: Cancelable = tasks.runCatching(api.fetchUsers()) {
case Right(value) => users.set(LoadState.Ready(value))
case Left(error) => users.set(LoadState.Failed(error.getMessage))
}
val dismiss: Cancelable = tasks.after(2.seconds) { notice.set(None) }
val poller: Cancelable = tasks.every(10.seconds) { reload() }

load.cancel() // Cancel one task without cancelling siblings.
tasks.close() // Keep the scope and call this from onLeave / onStop.

tasks.latest(key)(work)(onDone) is runCatching with latest-wins delivery: a new start under a key that already has a task in flight cancels that task and discards its result, even one already queued, so only the newest start per key is ever delivered — a search that reloads on every keystroke, or a run that can be restarted mid-flight. See Drop a stale response.

Each scoped operation returns a Cancelable. Submission, cancellation and close() are thread-safe. Both success and failure callbacks return to the scope's captured owner, even if submission happens on another thread. Closing is idempotent, rejects new submissions, cancels its timers and suppresses callbacks already queued but not yet admitted by their delivery guard. Runner retirement also closes its scopes, but screen departure needs an explicit close(). Create a fresh scope for every entry/run; a closed scope cannot be reopened.

Cancellation is best effort, not interruption or joining: work that has not started is skipped, but an admitted callback or blocking worker is allowed to finish. Closing never waits for it, cannot undo its side effects and cannot abort an HTTP request; configure IO timeouts or cooperative cancellation separately. Use tasks.runCatching inside scoped pollers too: an ordinary Async.run started by a scoped timer is still unscoped. Timer deliveries coalesce, but overlapping worker loads are not automatically single-flight; the application decides whether they are useful.

Reactive graph ownership​

Behavior change: being on some render thread no longer permits access to another runner's reactive graph. Signals, computeds and tracking scopes created on a runner bind to that owner; values constructed before startup bind their connected subscription graph on first owner access. Foreign tracked reads, mutations, subscription changes and disposal throw IllegalStateException. Nested runners are separate owners too, even on the same Java thread; the outer graph becomes usable again when control returns to the outer runner.

After the old owner retires, retained state may bind to the next run, so sequential app reruns remain supported. Runnerless sequential unit tests still need no runtime. Signal.peek remains a volatile, untracked cross-thread read; Computed.peek can rebuild dependencies and therefore remains owner-confined. Do not share one live graph between two runners. Pass immutable snapshots and start async work on the graph's owner instead.

Use the app tick for frame-oriented work​

Set RunnerConfig.tickRate when the whole application benefits from a regular heartbeat:

import scala.concurrent.duration.*

override def config = RunnerConfig(tickRate = Some(100.millis))

private val frame = Signal(0)

override def onTick(): Unit =
frame.update(_ + 1)

Key, mouse, and tick handlers already execute on the render thread, as do onStart and onStop. A tick that changes no signal causes no dependent computation to change; keep expensive work out of onTick itself.

Stopwatches and countdowns​

Stopwatch and Timer are caller-owned utilities advanced by the tick loop:

import io.worxbend.tui.runtime.Timer
import scala.concurrent.duration.*

private val timer = Timer(30.seconds)

override def config = RunnerConfig(tickRate = Some(100.millis))

override def onTick(): Unit =
timer.tick(100.millis)
if timer.justExpired() then notify("Time is up", NoticeLevel.Warning)

def timerView: Element = text(timer.formatted)

justExpired() returns true once, on the transition to zero, so side effects do not repeat on every later tick.

Integrate an existing callback API​

If a library owns its worker thread, marshal the callback manually:

// Capture during onStart, before the external callback runs.
val owner = RenderThread.capture()
client.onMessage { message =>
val _ = owner.execute {
messages.update(_ :+ message)
}
}

runOnRenderThread runs immediately when already on the UI thread and queues otherwise. runLater always queues rather than calling inline; work queued during a drain may run in that same batch if budget remains.

Each loop turn drains a bounded FIFO batch before returning to input, repaint and stop checks. Pending work stays queued and shortens the next input wait; a callback that queues its successor cannot monopolize the loop indefinitely. This bounds the number of callbacks, not the execution time of one callback: never block in one. Shutdown has a separate bounded final batch, then discards remaining callbacks when retiring the owner. Do not rely on an arbitrarily large backlog finishing before exit; perform required cleanup in the lifecycle callback instead.

When a continuation throws​

A queued continuation is your code, and your code throws — result.toOption.get on a failed request is enough. That no longer takes the app down: the render loop catches a non-fatal throwable from a queued body, reports it, and keeps draining, so the bodies queued behind it (a timer tick, a second in-flight request) still run in order.

By default the runner accumulates these failures and returns them once the app has exited, as Left(RunnerError.QueuedTask(QueuedTaskFailures(first, count))): count is how many bodies failed in total — a continuation that throws on every tick reports as the flood it was, not as one incident — and the later throwables are attached to first as suppressed exceptions, up to a bounded number, so their stack traces survive without a long-lived app hoarding them. If the backend then fails and ends the loop, Left(RunnerError.Backend(error, queuedTasks)) carries the same report rather than erasing it.

Install a handler to see each failure as it happens instead — reporting is then entirely yours, and run returns Right unless the backend itself failed. Keep the handler total: a handler that throws is not isolated, and takes the loop down with it.

override def config: RunnerConfig =
RunnerConfig(onTaskError = Some(error => lastError.set(Some(error.getMessage))))

The handler runs on the render thread, inside the drain, so it may set signals directly. Fatal errors (anything outside scala.util.control.NonFatal) still propagate and end the loop.

Failure and lifecycle checklist​

  • Model loading and failure in state; do not let worker exceptions vanish.
  • Cancel scheduled work when its screen or app feature is no longer active.
  • Never block in view, a key handler, onTick, or an Async completion callback.
  • Capture plain data in worker closures; terminal widgets and buffers belong to the render path.
  • Keep daemon work idempotent when retry is possible.

The complete HTTP example is examples/weather. Run it with ./mill examples.weather.run.