Skip to content

Comparison: twenty implementations of one pipeline ​

The capstone of the reactive-programming survey. Every deep-dive wrote the same worked pipeline: a query field → debounce N ms, N adjustable at runtime → hash a file set on a worker, a newer query cancelling the running hash → show the result, with a toggle that switches the whole pipeline off. This page lays the twenty answers side by side, extracts what they agree on, and maps each capability onto what event-horizon has today. Terms are defined in concepts.

Last reviewed: November 23, 2026


At a glance ​

SubjectModelLatest-wins formCancel waits?Built-in debounceInterval changeable while waiting?Value cellGlitch-freeVirtual time
RxJSpushswitchMapnodebounceTime (fixed), debounce(sel)next value only (debounce(sel))BehaviorSubjectnoTestScheduler (7.x); patched globals (9.x)
Effectpull, chunkedStream.switchMapyes (switchMap)Stream.debounce (fixed)noSubscriptionRefn/aTestClock
Kotlin Flowpush, suspendingtransformLatestyes (join)debounce { … }next value onlyStateFlownorunTest dispatcher
SwiftpullflatMapLatest; .task(id:)nodebounce(for:) (fixed)nonone (Observation)n/anone built in (swift-clocks)
Rustpollselect! loop; map_futurenononeyes (Sleep::reset)watch, Mutableundocumentedtokio pause/advance
fs2pull, chunkedswitchMapyes (finalizers)debounce (fixed, audit-like)noSignallingRefnoTestControl
Solid 2.0push-pullasync memonever cancelsnonen/asignalyesnone
TC39push-pullnonen/anonen/aSignal.Stateyesnone
Angularpush-pullresourcenodebounced (experimental)next value onlysignalyesTestBed.tick + fake timers
Composesnapshot stateLaunchedEffect(key)nononeyes, by keying on itMutableStateyesMainTestClock
Sodiumtransactional pushswitchS; .NET MapAsyncnononeyes (deadline cell)Cellyestimer system runTimersTo
Elmmodel-updatenone (sequence number)never cancelsnoneyes (per sleep)the modeln/aelm-program-test advanceTime
Esterel/Céusynchronouspar/or, abort … whenthreads: nonone (await N ms)with a third race branchvariablesby constructionemit time from async
C++ senderslazy single-valuenone (scope + stop source per request)composites: yes; spawned: nononeyes (an argument to schedule_after)nonen/anone (fake a timed_scheduler)
Rx.NETpushSelect(f).Switch()no (AsyncRx: yes, unreleased)Throttle (fixed), Throttle(selector)next value only (selector)BehaviorSubjectnoTestScheduler, HistoricalScheduler
Pekko Streamsdemand-drivenswitchMap (1.2.0)nonone (switchMap + initialDelay)next value onlynonen/aManualTime (process-wide)
Transducerspush into a stepnone (hand-written go-loop)never cancelsnone (alts! + timeout)yes, in hand-written codenone (atom, sliding channel)n/anone (wall-clock timers)
Reflexpush-pull, framesswitchHold, switchDynnever cancelsdebounce (fixed)no (user code sampling a Behavior)Dynamicyesnone (frame-by-frame test plans)
Yampasampled dataflowrSwitchn/a (pure)none (localTime after a restart)yes (compared on every sample)none first-classby constructionembed with explicit dt
Incrementalexplicit stabilisebindn/a (no async)none (bind over Clock.after)yes (an input of the bind)VaryesClock.advance_clock

Latest wins and the cancel-wait split ​

Every subject can express latest-wins; they differ in what abandoning the old work means.

  1. Cancel-and-join (Kotlin, fs2, Effect's switchMap). The replacement starts only after the cancelled run has finished, finalizers included. fs2 states it in the scaladoc ("Finializers of each inner stream are guaranteed to run before the next inner stream starts") and enforces it with a one-permit semaphore; Kotlin's transformLatest calls cancel(), then join(), then launch. The cost is latency: the switch waits for the old work to reach a cancellation point.
  2. Cancel-and-forget (RxJS, Swift, Rust, Compose, Angular, TC39 user code, Sodium's .NET MapAsync). The replacement starts at once and a generation check drops the stale result. Old and new CPU work overlap until the old one notices.
  3. Discard only (Solid, Elm). Nothing is told to stop; the stale result is ignored. Solid's RFC: "Solid drops a superseded run's result on its own; stopping the work itself is up to the run."
  4. Lexical abortion (Céu). The losing trail of a par/or dies in the same reaction, finalizers run, and nothing is left to discard. A hashing thread is the exception: it is flagged and reaped later.

Effect is split internally: Stream.switchMap joins, FiberHandle.run and Atom do not. A library that offers latest-wins has to choose one rule and state it.

C++ senders make the split by construction. The composite algorithms (when_all in C++26, exec::when_any in stdexec) request stop on the other children and complete only after every child has, the rule event-horizon's race already follows. There is no latest-wins algorithm at all: it is built from a counting_scope, a stop source per request and a generation check, which forgets by default and joins only when each request is chained on its predecessor's spawn_future.


Debounce ​

No surveyed library's debounce operator handles an interval that changes while a wait is pending. The built-in operators fix the duration at construction (Effect, Swift, fs2, RxJS debounceTime) or read it once per value when the value arrives (RxJS debounce(selector), Kotlin debounce { … }, Angular debounced). fs2's debounce is not even a trailing debounce: it fires N after the first value of a burst.

The consensus is to build debounce from latest-wins: the inner work begins with a sleep on the current interval, and the next value cancels it, whether it is still sleeping or already hashing.

SubjectDebounce as a sleep inside latest-wins
EffectStream.switchMap(q => sleep(Ref.get(n)) then hash(q))
KotlintransformLatest { delay(n.value); emit(hash(it)) }
fs2switchMap(q => Stream.sleep(n.get) ++ hash(q))
ComposeLaunchedEffect(query) { delay(n); hash(query) }
Swift.task(id: query) { try await Task.sleep(for: n); … }
Rustmap_future around a sleep, or Sleep::reset(last + n)
Céupar/or do await (n)ms; hash with await QUERY end
Sodiuma deadline cell fed to the timer system's at
C++ sendersschedule_after(sch, n) | let_value(hash) inside a spawned, stoppable request

This collapse has a second benefit the separate-operator form lacks. With debounce followed by switchMap, a keystroke during a hash cancels it only N later, when the debounced value arrives (Kotlin, Compose both document the difference). With the sleep inside, the keystroke cancels the hash at once.

The interval becomes changeable in two strengths. Reading it at the start of each sleep applies a change from the next keystroke. Making the interval an input of the latest-wins key (Compose keys on both; Céu adds a third race branch) restarts a pending wait at once, at the cost of re-hashing an unchanged query.

On cost: RxJS 7's debounceTime and Swift's debounce do not re-arm a timer per value. They record the last arrival and let one long-lived timer re-check its deadline on waking. RxJS 9 dropped the optimisation (decision D-019).


Cells and streams ​

Every mature design separates value cells from event streams:

  • Kotlin has StateFlow (conflated, always has a value, never completes) beside SharedFlow and Flow.
  • Sodium's whole API is Cell versus Stream, joined only by hold, snapshot and sample.
  • Compose makes conflation a principle and tells users not to model events as state.
  • Signals libraries (Solid, TC39, Angular) are cells only; their bridges to streams (Angular's toObservable) are lossy and asynchronous.

The cells differ in what a slow reader sees. StateFlow, watch, Mutable and signals keep only the latest value; Effect's SubscriptionRef.changes replays every update through an unbounded PubSub, so conflation has to be added downstream.

The worked pipeline needs both: the query, the toggle and the interval are cells; nothing in it is an event that must not be lost.


Errors ​

Two positions:

  • An error ends the stream (RxJS, Kotlin Flow, fs2, Swift). A failed hash inside the inner kills the pipeline unless it is caught inside the inner and turned into a value.
  • An error is a value or a status (Effect's Exit/Cause, Angular's resource status, Solid's errored node, TC39's cached exception, Elm's Result in a message).

Effect adds the distinction that matters for latest-wins: interruption is neither success nor failure. A superseded hash must not surface as an error, and must not be mistaken for a result. C++ senders make it a channel of its own: every operation completes exactly once, on set_value, set_error or set_stopped, and spawn drops a stopped completion silently, which is the behaviour a superseded request wants. Compose shows the failure mode: a broad catch swallows the cancellation and silently breaks latest-wins.


Lifetime and ownership ​

MechanismSubjects
Structured scopes (cancel propagates down)kotlin-flow, fs2, effect-ts, synchronous-languages (lexical), cpp-senders-receivers (counting_scope; destroying one unjoined terminates)
Manual subscriptionsrxjs (takeUntil(destroy$)), swift-async-algorithms (unstructured Tasks inside operators)
Injection-context teardownangular-signals (DestroyRef)
Owner treesolid-signals
Keyed slots in the UI treejetpack-compose, SwiftUI .task(id:)
Declarations diffed by the runtimeelm (subscriptions model)
Garbage collectionsodium, tc39-signals (unwatched nodes)

The toggle is the test of a lifetime model. Where lifetime is structural — Elm's if model.on then … else Sub.none, Compose's if (enabled) LaunchedEffect, Céu's watching — switching off cancels the pending debounce and the running hash with no extra code. Where it is an operator (switchMap(on => on ? src : EMPTY) in RxJS, Effect, fs2, Kotlin), the result is the same but must be composed explicitly. Effect's Stream.when looks like a toggle and is not: it checks once, at start.


The frame ​

Four subjects give a frame a reactive meaning, and they agree on its shape:

  • Sodium: one transaction is one instant. Every read sees the previous transaction's committed values; every hold commits at the end.
  • Esterel and Céu: one reaction runs every awakened trail to completion before the next input is read.
  • Angular: one change-detection tick flushes root effects, then refreshes views; each effect-driven hop costs one tick.
  • Compose: global snapshot writes are coalesced, then one recomposition runs per frame.

The shared lesson: inputs are applied between frames, and a frame reads one consistent snapshot. Sparkles apps already rebuild their widget tree every frame, so they need no read tracking to decide what re-runs (Compose's conclusion). What they lack is the lifetime half: which work stays alive between frames.

Two hazards recur. Solid's pending async value throws when read outside a tracking scope, and a per-frame rebuild reads everything outside one: a frame needs a non-throwing read returning pending, a value or an error. Sodium's hold delay means that in the transaction where the interval changes, sampling it still returns the old value.


Virtual time ​

Everyone who tests debounce deterministically does it with virtual time, and three lessons recur:

  1. The clock must be injected, not patched. RxJS 7 passes a scheduler with now(); RxJS 9 removed schedulers and patches globalThis timers, and its own decision record admits that timers captured before the patch escape.
  2. The worker executor must be under the test clock too. Kotlin's Dispatchers.Default, Compose's off-main work and tokio's blocking pool all escape virtual time unless injected; fs2's TestControl treats waiting on an external thread as a deadlock.
  3. Advancing must run what became due, then wait for it to settle. Effect's TestClock.adjust wakes sleepers one deadline at a time and waits until the woken fibers are idle; Kotlin's advanceTimeBy excludes its end point, so a timer due exactly then needs runCurrent().

API structure and naming ​

The second-wave deep-dives each carry an API structure and naming subsection (Rx.NET, Pekko, transducers, Reflex, Yampa, Incremental). Read together with the first wave, they agree on six points, and their regrets are more instructive than their designs.

1. Sources, transforms and sinks are different kinds of thing. The libraries that make the split a type split age best. Pekko has Source, Flow and Sink blueprints that do nothing until a RunnableGraph is materialised. Incremental has Var (input), Incr (derived) and Observer (sink), with one one-way conversion between each. Transducers separate the transformation from both the process that applies it and the reducing function that receives it. Effect makes running a stream a run* family that returns the single-value type (Effect: runCollect, runDrain, runFold). Rx.NET puts all three on one static Observable class, split over 18 files, and its Qbservable ADR has to name the split after the fact ("factory-like" versus "combinator-like" operators).

2. An operator is written once, for every source kind. Pekko defines each operator once in FlowOps, and the return type follows the receiver (a Source stays a Source). Transducers run the same map, filter, dedupe and scan over collections, lazy sequences and channels; core.async then deprecated its parallel channel family (map<, filter>, unique) with "Use transducer instead". The boundary is the same everywhere: per-element operators can be source-independent; operators that need time (debounce), concurrency (switch) or several inputs (merge) cannot, and core.async writes those as go processes.

3. A second type channel is expensive. Pekko's materialised-value parameter Mat forces 27 …Mat twins in scaladsl/Flow.scala, Keep.left/right/both, and a series of escape hatches (preMaterialize, Sink.source). Effect's R channel is the same cost paid for dependency injection. A sink that returns one Effect and handles (queues, cells, cancel tokens) created before the pipeline avoid it.

4. Variant axes become parameters, not names. Every long-lived library grew a suffix grammar, and the later releases fold it back into arguments:

LibraryGrammarWhat happened
Yampad/r/k/p prefixes, B/Z, Cat, By: 22 switch namesdocumented in the source; still the hardest part of the API
ReflexDyn, B, E, With, Maybe, M, ', Promptly, Cheapstacks to attachPromptlyDynWithMaybe; the safe default got the short name
Rx.NET (System.Linq.Async)SelectAwait, WhereAwait, SelectAwaitWithCancellationretired in .NET 10 for overloads that always take a token
Effect v4catchAll → catch, catchSome → catchFilter; fork → forkChildconcurrency and discard moved into an options object ({ concurrency, discard })
PekkoflatMapConcat/flatMapMerge, …Unordered, …Within, …Weightedregular, but latest-wins is switchMap, outside the flatMap… family
Incremental_exn, map2…map15, ', opt_; an Expert submodulemechanical and uniform; the sugar (Let_syntax) builds more nodes than mapN

The renames in Effect v4 are recorded in its migration notes (error-handling.md, forking.md). Distinct names are kept for distinct semantics: merge versus switch versus concat, ordered versus Unordered.

5. A name is chosen for the semantics, once. The most-cited regret in the survey is Rx.NET's Throttle, which is a debounce; its packaging ADR is premised on "almost nobody likes Throttle". The same word means two things across the catalog: a trailing debounce (RxJS' debounceTime) and an audit (fs2's debounce). Reflex renamed switchPromptly to switchHoldPromptly to group operators by how they are built. Renames cost a major version in Pekko (TestSource.probe → TestSource()).

6. Free-function operators collide. In .NET 10, two libraries defining Select on IAsyncEnumerable became an ambiguity error and forced the AsyncEnumerableDeprecated rename. D's UFCS has the same failure mode: a stream map beside std.algorithm.map, or an operator struct named like event-horizon's own Mapped and Zipped. One canonical module per operator family, with aliases in separately imported modules, keeps resolution predictable.

Two documentation practices are worth copying. Pekko's operator index sorts about 230 operators into 17 categories, and every operator page carries the same four lines: emits when, backpressures when, completes when, cancels when. Reflex's Quickref groups functions by the type they return and tags each with the capability it needs to run.


The consensus standard ​

What a reactive library for a structured-concurrency loop should provide, as far as twenty designs agree:

  1. Latest-wins is the primitive — a switch that owns a child scope per value and cancels it on the next one. Debounce, toggles and restarts are built from it.
  2. One stated cancel rule. Join or forget, chosen once and documented; the libraries that mix them (Effect) are the ones whose docs have to warn about it.
  3. Value cells distinct from event streams, cells conflating.
  4. Interruption is a third outcome, never an error and never a value.
  5. Cancellation reaches CPU work through cancellation points — chunk boundaries or explicit checks — because nothing preempts.
  6. An injectable clock, with the worker executor reachable from tests.
  7. A frame reads a consistent snapshot, and a pending value is readable without throwing.

Architectural trade-offs ​

DecisionOption AOption B
Cancel semanticsjoin: serial resources, higher switch latencyforget: low latency, overlapping CPU work
Debouncean operator (familiar, fixed or per-value N)a sleep inside latest-wins (one mechanism, dynamic N)
Where streams livea stream library over the loop (Rx, Effect, fs2)keyed effects in the UI tree (Compose, SwiftUI, Elm)
Evaluationpush (simple, no backpressure)pull (backpressure, chunking, more machinery)
Glitch handlingnone (streams)transactions or push-pull (cells)

Delta: what event-horizon has and what is missing ​

CapabilityPrior artevent-horizon todayGap
Lazy single-value effectEffect Effect, cats-effect IOEffect: succeed, fail, map, andThen, zipPar, withRetry, withTimeoutnone for one value; no multi-value stream
Structured scopes and cancelKotlin CoroutineScope, fs2 scopesScope: spawn, cancel, onExit, withScope, withDeadlinenone
Race / first-winspar/or, select!, exec::when_anyracenone
Stop-token joiningC++ stop-when (exposition-only); write_env replaces insteadthe fiber context's interrupt, inherited down a scopecombine a per-request token with the scope's
Latest-wins switchswitchMap, transformLatest, LaunchedEffect(key)none as a primitive; hand-written four times (hue's FormatFlow, the picker, grep, font preview)the core gap
Debouncesleep inside latest-winssleep/sleepUntil, Tickerfalls out of the switch
Value cell (multicast, conflating)StateFlow, watch, Mutable, signalsnone; Channel is a unicast queuenew
Cross-thread delivery to the UICrossChannel, watchCrossChannel (tryTake from any thread), the loop's wakernone
CPU work off the loopwithContext(Default), blocking, WorkersJobQueue, RawCpuPool, BlockingPool, ForkServercancellation of an accepted job is cooperative only
Cancellation point in CPU workfs2 chunk steps, ensureActiveinterruptRequested for fibers; nothing for pool jobsa token a worker can poll
Interruption as a third outcomeEffect Exit/CauseECANCELED as an IoErrordecide whether a superseded result is an error
Virtual timeEffect TestClock, TestControlTestClock with advance/advanceToNextthe worker pool under the test clock
Frame integrationSodium transactions, Compose framesthe UI host's wakeIn per frame; no event-horizon loop on the native window armdecide where the pipeline runs

The core gaps are three: a latest-wins switch, a value cell, and a decision on where a pipeline runs relative to the UI frame. Everything else exists.