Swift Async Algorithms and structured concurrency streams (Swift)
Pull-based asynchronous sequences on top of Swift's structured concurrency: the standard library's AsyncSequence/AsyncStream, cooperative Task cancellation and the Clock protocol, plus Apple's swift-async-algorithms package of time and combining operators (debounce, combineLatest, merge, flatMapLatest, AsyncChannel, AsyncTimerSequence). SwiftUI's .task(id:) and the Observation framework complete the UI side.
| Field | Value |
|---|---|
| Language | Swift 6.x (the package manifest declares swift-tools-version: 6.2, Package.swift) |
| License | Apache-2.0 with Runtime Library Exception (LICENSE.txt) |
| Repository | apple/swift-async-algorithms |
| Documentation | DocC guides under Sources/AsyncAlgorithms/AsyncAlgorithms.docc/Guides/; proposals under Evolution/; standard library at developer.apple.com/documentation/swift |
| Category | pull-based asynchronous streams over structured concurrency (async iterators, not observers) |
| Versions surveyed | main at commit 088f92a30c10 (2026-11-18). Availability macros run AsyncAlgorithms 1.0 to 1.3 (Package.swift); release tags were not in the shallow clone, so the mapping of operators to tagged releases is (unverified) |
| Core abstraction | AsyncSequence, whose iterator's async next() returns the next element or nil at the end; the consumer pulls, and the producer suspends until it does |
NOTE
This deep-dive spans three layers that ship separately: the Swift standard library (AsyncSequence, AsyncStream, Task, Clock; cited from Apple's documentation), the swift-async-algorithms package (cited from source at the SHA above), and the Apple UI frameworks (SwiftUI .task(id:), Observation). Claims about the first and third rest on Apple's documentation, not on source.
Overview
What it solves
Swift 5.5 (2021) added async/await, structured tasks and the AsyncSequence protocol, so for await x in seq became the language-level way to consume values over time. The standard library ships only the sequential operators (map, filter, prefix, …) and one bridge type, AsyncStream. Everything about time (debounce, throttle, timers) and about combining several sources (merge, combineLatest, zip, switching) lives in swift-async-algorithms. The README states that scope (README.md):
"AsyncAlgorithms is a package for algorithms that work with values over time. That includes those primarily about time, like
debounceandthrottle, but also algorithms about order likecombineLatestandmerge. Operations that work with multiple inputs (likezipdoes onSequence) can be surprisingly complex to implement, with subtle behaviors and many edge cases to consider."
It is the Swift counterpart of Kotlin Flow: both are cold, suspension-based streams whose operators are coroutines, and neither has an observer interface like RxJS's. Swift has one property Kotlin lacks. An AsyncSequence has no "collector scope" of its own, so any operator that must run concurrently with its consumer (debounce, merge, flatMapLatest) has to spawn a Task internally.
Design philosophy
The README frames the package as structured concurrency applied to streams (README.md):
"Structured concurrency allows us to write code where intermediate state is simply a local variable,
trycan be used directly on functions thatthrow, and generally treat the logic for asynchronous code similar to that of synchronous code."
Three consequences shape the API:
- Pull, with demand propagated upstream. No operator runs ahead of its consumer. Even
debounce, which needs a concurrent upstream reader, only lets that reader pull again after the downstream has callednext(). Back-pressure is built into the model, not bolted on. - Time is a generic
Clockparameter. Every time-based operator takesclock: CwhereC: Clock, so tests substitute a manual clock without a scheduler abstraction. This is theClock/InstantProtocol/DurationProtocoltriple from the standard library. - Sendability is part of the signature. An operator that spawns tasks requires
Base: Sendable, Element: Sendable. The effects table (Effects.md) listsAsyncDebounceSequenceasSendableand its iterator asNot Sendable: one consumer per iterator, enforced by the compiler.
How it works
The protocol pair is minimal. Apple's documentation of AsyncIteratorProtocol (docs):
"The protocol defines a single asynchronous method,
next(), which either produces the next element of the sequence, or returnsnilto signal the end of the sequence. … After returningnil(or throwing an error) fromnext(), the iterator enters a terminal state, and all future calls tonext()must returnnil."
The same page says iterators handle cancellation themselves: by checking Task.isCancelled and returning nil, by calling checkCancellation(), or by wrapping next() in withTaskCancellationHandler. That is the whole cancellation contract. There is no dispose; a consumer stops by leaving its for await loop, which drops the iterator, or by having its task cancelled.
Bridging from callbacks: AsyncStream. A stream is built from a closure that receives a Sendable Continuation; yield(_:) pushes, finish() ends (docs). AsyncStream.makeStream(of:bufferingPolicy:) returns the (stream, continuation) pair directly (docs). The buffer is the only place where push meets pull, and its policy is chosen up front (docs):
AsyncStream.Continuation.BufferingPolicy | When the buffer is full |
|---|---|
.unbounded (default) | "Continue to add to the buffer, without imposing a limit" |
.bufferingOldest(n) | "discard the newly received element" |
.bufferingNewest(n) | "discard the oldest element in the buffer" |
.bufferingNewest(1) is a conflating latest-value cell, the natural shape for a text field's change events. AsyncStream.yield never suspends, so AsyncStream has no back-pressure. AsyncChannel (below) is the back-pressured alternative.
Operators that need concurrency spawn tasks. In the package source, these storage types create unstructured Task { … }s: DebounceStorage, FlatMapLatestStorage, MergeStorage, CombineLatestStorage, ZipStorage, AsyncShareSequence, the buffer storages and the multi-producer channel. Each type is a lock-protected state machine (*StateMachine.swift) plus a storage class that turns the machine's returned actions into continuation resumes and task.cancel() calls. debounce is typical (DebounceStorage.swift):
let task = Task {
await withThrowingTaskGroup(of: Void.self) { group in
// The task that consumes the upstream sequence
group.addTask { … }
// This is our clock scheduling loop
group.addTask { … }
}
}The outer Task is unstructured, so it does not inherit the consumer's cancellation. The storage reaches it by hand: the consumer's next() runs inside withTaskCancellationHandler and its onCancel calls task.cancel(), and the iterator's deinit (through an InternalClass wrapper, "to hook the deinit" per AsyncDebounceSequence.swift) does the same.
Evaluation model
- Pull. A value moves only when someone awaits
next(). Push sources (UI callbacks, notifications) enter through anAsyncStreambuffer or anAsyncChannel. - Lazy and cold. Building
query.debounce(for: .milliseconds(250))stores the base, interval and clock and starts nothing.makeAsyncIterator()creates theDebounceStorage, and the firstnext()creates its task (state.initial→.startTask). Each iterator gets a private copy of the pipeline. Hot behaviour needsshare()(below). - Asynchronous propagation; no glitch-freedom guarantee. Every hop through a multi-input operator is a continuation resume handled by the concurrency runtime.
combineLatest(a, b)emits a tuple per upstream element, so a "diamond" (combineLatest(x.map(f), x.map(g))) yields intermediate mixed tuples. Nothing provides a transactional snapshot. That is the job of signals and of Observation's transactions (State and sharing). - Single consumer per iterator. Iterators of the time and combining operators are
@available(*, unavailable) … Sendable(AsyncDebounceSequence.swift), so an iterator cannot leave its task.
Composition
- Standard library: the
Sequence-shaped operators onAsyncSequence(map,compactMap,flatMap(concatenating),filter,prefix,drop(while:),reduce,contains, …) (names per Apple docs; not re-verified here). - Package, combining:
chain,combineLatest(2 and 3 inputs),merge(2 and 3),zip(2 and 3),joined(separator:), andflatMapLatest(README.md,FlatMapLatest.md). The guides give the fixed-arity reason: "This function family and the associated family of return types are prime candidates for variadic generics. Until that proposal is accepted, these will be implemented in terms of two- and three-base sequence cases" (Merge.md,CombineLatest.md). - Package, time:
debounce,_throttle,AsyncTimerSequence, pluschunks(ofCount:or:)with a timer signal. - Package, others:
adjacentPairs,chunked,compacted,removeDuplicates,interspersed,buffer(policy:),share(bufferingPolicy:),mapError, and collection initialisers (Array(seq),Dictionary(…),Set(…)).
That makes about 25 operators, against roughly 115 in RxJS. Anything missing is written as an async function or a hand-rolled iterator. That is idiomatic in Swift and needs no escape hatch.
IMPORTANT
A flatMapLatest exists at this SHA, as Evolution/0018-flatMapLatest.md (status "Proposed") with source and tests, gated @available(AsyncAlgorithms 1.3, *) (AsyncFlatMapLatestSequence.swift, proposal). It is not yet listed in the README, and its concrete type is internal: the public API returns some AsyncSequence<T.Element, T.Failure> & Sendable. The proposal rejects RxJS's name: "switchMap: Used in ReactiveX, but "switch" in Swift has strong association with control flow statements", and takes RxSwift's flatMapLatest instead. The idiomatic alternative, which predates the operator, is the hand-rolled cancel-and-replace Task shown in Concurrency and cancellation.
Derived values are ordinary code: seq.map { … } or a computed property on an @Observable model. There is no memoised derived-value node.
Time and scheduling
Clock. The standard library protocol is "a mechanism in which to measure time, and delay work until a given point in time" (docs). It has now: Instant, minimumResolution: Duration and sleep(until:tolerance:). On tolerance, the docs say: "The clock may reschedule tasks within the tolerance to ensure efficient execution of resumptions by reducing potential operating system wake-ups." Instant: InstantProtocol supplies advanced(by:) and duration(to:) (docs). The concrete clocks are ContinuousClock (keeps counting while the system sleeps), SuspendingClock (stops while it sleeps) and user types. A clock is not a scheduler: it does not pick the thread or executor where the woken task resumes. That is the task's actor isolation or executor.
Executors, not schedulers. Where code runs is decided by isolation: @MainActor, a custom actor, or the global concurrent pool. Swift 6.2's @concurrent and default nonisolated(nonsending) semantics move a function off the caller's actor (language feature; cited from memory of SE-0461, not verified here). No operator in the package takes a scheduler argument. Operators that spawn Tasks run on the global executor.
How debounce is implemented. debounce(for:tolerance:clock:) stores the interval as private let interval: C.Instant.Duration (AsyncDebounceSequence.swift#L42). The storage task runs two children in a task group:
- The upstream loop waits on a continuation until the downstream signals demand, pulls
iterator.next(), and records each element withdeadline = self.clock.now.advanced(by: self.interval)(DebounceStorage.swift#L175). - The clock loop waits for a deadline and calls
try await self.clock.sleep(until: deadline, tolerance: self.tolerance)(DebounceStorage.swift#L261). On waking it asks the state machine whether the current element's deadline has passed (DebounceStateMachine.swift#L546):
case .debouncing(let task, let upstreamContinuation, let downstreamContinuation, let currentElement):
guard currentElement.deadline <= self.clock.now else {
// The deadline is still in the future so we need to sleep again
return .none
}A newer element does not cancel the sleeping timer. It only moves the deadline, and the clock loop goes back to sleep until the new one. This is the "lazy re-arm" debounce (one sleeper, re-check on wake), not RxJS-style cancel-and-reschedule. A finish or a thrown error is forwarded at once, with the pending element flushed first (test_finishDoesntDebounce, test_throwDoesntDebounce in TestDebounce.swift).
WARNING
The debounce duration cannot change at runtime. It is a let captured at construction and copied into the storage (DebounceStorage.init(base:interval:tolerance:clock:)). There is no overload that takes a duration-producing closure or a sequence of durations, and the guide's only alternative is a reducing debounce (Debounce.md). To change N you rebuild the pipeline: cancel the consuming task and start a new iterator. Any element pending in the old debounce is lost.
throttle is underscored. The public entry points are _throttle(for:clock:reducing:) and _throttle(for:clock:latest:) (AsyncThrottleSequence.swift), although proposal SAA-0014 is "Accepted" (0014-rate-limits.md) and the README lists throttle(for:clock:reducing:). The README's stability rule puts it outside the API contract: "The public API of version 1.0 … will consist of non-underscored declarations" (README.md). The implementation spawns no task and measures elapsed time inside next() (#L103). Its interval is a let too.
AsyncTimerSequence computes next = (last ?? clock.now).advanced(by: interval) and sleeps until then, so it does not drift. On cancellation it returns nil rather than throwing (AsyncTimerSequence.swift; guide: "If at any point in time the task executing that iteration is cancelled the iteration will return nil", Timer.md). .repeating(every:) defaults to SuspendingClock.
Concurrency and cancellation
Cooperative, flag-based cancellation. task.cancel() sets a flag and runs any registered handlers. Apple's docs on Task.isCancelled (docs): "After the value of this property becomes true, it remains true indefinitely. There is no way to uncancel a task." The same page notes that a newer withTaskCancellationShield(operation:) can hide the flag inside a region. Task.checkCancellation() throws CancellationError (docs). withTaskCancellationHandler(operation:onCancel:isolation:) is the hook that wakes suspended work (docs):
"the cancellation handler is always and immediately invoked when the task is canceled. … If cancellation occurs while the operation is running, the cancellation handler executes concurrently with the operation. Cancellation handlers which acquire locks must take care to avoid deadlock."
Cancellation flows down the structured tree (child tasks, async let, task groups), not into unstructured Task { }. It never preempts: a CPU-bound loop that does not check stays uncancelled until it returns. The standard library's Task.sleep and clock.sleep are cancellation points that throw CancellationError at once.
Does a cancel wait for the cancelled work? cancel() does not. Only structure waits: a task group or async let scope cannot exit before its children finish, so cancelling a group and then leaving it is a cancel-and-join. In flatMapLatest, switching is cancel-and-forget (FlatMapLatestStorage.swift#L172):
case .startInnerTask(let inner, let generation, let previousTask, let previousCont):
if let previousTask = previousTask {
previousTask.cancel()
previousCont?.resume(throwing: CancellationError())
}
startInnerTask(inner, generation: generation)The old inner Task may still be running a CPU-bound step while the new one starts. Stale output is filtered by a generation counter, not by joining: the proposal says "Each new inner sequence is assigned a generation number. Elements from stale generations are discarded" (proposal). The outer reader pulls the base only while the downstream has demand pending (outerTaskSuspended: "If we have downstream demand, resume immediately"). A consumer suspended in next(), waiting for a hash, therefore still sees a newer query.
The hand-rolled latest-wins, idiomatic before flatMapLatest and still common, is a stored Task handle:
@MainActor final class Searcher {
private var current: Task<Void, Never>?
func submit(_ query: String) {
current?.cancel() // cancel, do not wait
current = Task { [weak self] in
guard let digest = try? await hashFileSet(matching: query),
!Task.isCancelled else { return } // drop a result that lost the race
self?.show(digest)
}
}
}The !Task.isCancelled check after the await is required. Cancellation does not stop a computation that has already returned, so without it a stale result can still be written.
CPU-bound work. Task.detached or a @concurrent function (Swift 6.2) puts work on the global cooperative pool, which has about one thread per core. A long hash blocks one of those threads, and other tasks are not preempted off it. The hash must check Task.isCancelled or call try Task.checkCancellation() between files and call await Task.yield() to share the pool. A dedicated thread or DispatchQueue needs a hand-written bridge through withCheckedThrowingContinuation plus withTaskCancellationHandler.
Errors and completion
- Typed failure. Since Swift 6.0 (SE-0421, cited from memory),
AsyncSequencehas aFailureassociated type (AsyncSequence<Element, Failure>) andnext(isolation:) async throws(Failure).flatMapLatestis overloaded three ways to unifyNeverwith a real failure, usingmapError { _ in fatalError() }as a type-level cast (AsyncFlatMapLatestSequence.swift).mapErroris a package operator (SAA-0017). rethrowspropagation. Most operators arerethrows: they throw only if the base throws (Effects.md). An error ends the sequence; there is nocatch/retryoperator. Recovery means ado/catcharound thefor try awaitloop and a new iterator.- Completion is
nil. ForflatMapLatest, the proposal says "The sequence completes when: 1. The base sequence finishes producing elements, AND 2. The final inner sequence finishes producing elements". An error from the base or from any inner sequence "is immediately propagated and all tasks are cancelled" (proposal). - Cancellation is not an error at the sequence level for non-throwing sequences.
AsyncTimerSequenceandAsyncChannelreturnnilwhen cancelled. Throwing sequences may surface aCancellationError, which the consumer must tell apart from real failures. - Errors-as-values are a user choice (
Result<T, E>elements), not a library convention.
State and sharing
- No value cell in the stream library. Neither the standard library nor the package has a
BehaviorSubject/StateFlowequivalent. Current state lives in an@Observableclass or an actor, and streams carry changes. - Observation (SE-0395, Swift 5.9).
@Observablemacro-expands stored properties intoObservationRegistraraccesses.withObservationTracking(_:onChange:)"tracks access to any property within theapplyclosure, and informs the caller of value changes made to participating properties by way of theonChangeclosure" (docs). SE-0395 says theonChangeclosure "is then called on the first change", so it is one-shot. The proposal's example re-arms it by callingwithObservationTrackingagain from insideonChange(SE-0395). This is the dependency-tracking primitive SwiftUI uses to invalidate a view body. It is push-on-invalidate, pull-on-read: closer to signals than to streams. Observations(iOS/macOS 26). AnAsyncSequenceover an@Observableexpression: "track changes to types that are marked as@Observableby using Swift Concurrency to indicate transactional boundaries starting from the willSet of the first mutation to the next suspension point of the safe access" (docs). Mutations made within one synchronous stretch coalesce into one element. This is a glitch-free, conflating bridge from state cells into streams.- Multicast:
share(bufferingPolicy:)(SAA-0015, accepted). Each consumer "independently can make forward progress and get the same values but do not replay from the beginning of time" (Share.md). The default policy is.bounded(1)(AsyncShareSequence.swift). There is no replay orshareReplay. - Back-pressured hand-off:
AsyncChannel. "Each value sent by the channel will await the consumption of that value by iteration. … the rate of production cannot exceed the rate of consumption" (Channel.md).sendsuspends until anext()takes the value,finish()resumes every pending sender and receiver, and "The calls tosend(:)andnext()will immediately resume when their supporting task is cancelled".MultiProducerSingleConsumerAsyncChannel(SAA-0016, "Implemented") adds a buffered, watermark-based strategy (.watermark(low:high:)) (source). - Conflation comes from
AsyncStream's.bufferingNewest(1),buffer(policy:), orremoveDuplicates().
Lifetime and ownership
- The consuming task is the owner. A pipeline lives exactly as long as the task iterating it. Cancelling that task cancels
next(), whosewithTaskCancellationHandlercancels each operator's internalTask(debounce:.resumeDownstreamContinuationWithNilAndCancelTaskAndUpstreamAndClockContinuation). - Dropping the iterator also tears down, through the
InternalClass.deinithook inAsyncDebounceSequence.Iterator. The package comments: "If we get move-only types we should be able to drop this class and use thedeinitof theAsyncIteratorstruct itself" (AsyncDebounceSequence.swift). - Unstructured tasks leak by default. A
Task { }stored nowhere runs to completion. One that capturesselfstrongly keeps its object alive while it loops on an infiniteAsyncStream. Teardown is manual (task.cancel()indeinitoronDisappear) unless SwiftUI owns the task. - SwiftUI
.task(id:)binds a task to a view's lifetime (docs): "SwiftUI can automatically cancel the task after the view disappears before the action completes. If theidvalue changes, SwiftUI cancels and restarts the task." It comparesidwithEquatable, so it is latest-wins built into the view tree. The current signature istask(id:name:priority:file:line:_:).name,fileandline"[are] a no-op prior to iOS 26.4"; earlier SDKs havetask(id:priority:_:). Whether SwiftUI waits for the cancelled task before starting the new one is undocumented (unverified; assume it does not). AsyncStream.Continuation.onTerminationruns when the consumer cancels or finishes, and is the place to unregister a callback source.
Testing
- No virtual clock ships in the standard library or in the
AsyncAlgorithmsproduct. The package's own tests use two test-only clocks. Neither is a product (Package.swiftexports onlyAsyncAlgorithmsandAsyncStreaming).ManualClock(Tests/…/Support/ManualClock.swift):InstantandStepare integer ticks, withadvance()/advance(by:)and asleep(until:)that suspends until the clock passes the deadline.AsyncSequenceValidation, a marble-diagram DSL with its ownClock(Validation.md). It makes scheduling deterministic by installingswift_task_enqueueGlobal_hookso every global job runs on its own driver thread (Test.swift#L383). The guide argues that "Taking the approach of having explicit ordering of time defined by the diagram allows for the test to be predictable." A debounce test (TestDebounce.swift):
validate {
"abcd----e---f-g----|"
$0.inputs[0].debounce(for: .steps(3), clock: $0.clock)
"------d----e-----g-|"
}- Community:
pointfreeco/swift-clocks(MIT, 1.1.1) providesTestClock, "a clock whose time can be controlled in a deterministic manner … useful for testing … timers,debounce,throttle,timeout, and more", withadvance(by:)andrun(), and alsoImmediateClockandUnimplementedClock(docs, package). The pattern is to injectany Clock<Duration>into the model. - The gap:
Task.sleep(for:)without a clock argument, and SwiftUI's.task(id:)scheduling, cannot be virtualised. Code that should be testable must take aClockparameter. Driving real tasks under aTestClockalso needs the consumer to reach its suspension point beforeadvanceis called, a known source of flaky tests thatAsyncSequenceValidationsolves only by hooking the global executor.
The worked pipeline
Query field → debounce N ms (N adjustable at runtime) → hash a file set on a worker with latest-wins cancellation → show the result. A toggle enables or disables the whole pipeline.
Variant A: SwiftUI .task(id:) (idiomatic). The id is the whole configuration. Debounce becomes a cancellable sleep at the start of a restartable task, and latest-wins comes free:
struct PipelineKey: Equatable { var query: String; var delay: Duration; var enabled: Bool }
@MainActor @Observable final class Model {
var query = ""
var delayMs = 250
var enabled = true
var result: Result<String, Error>?
var key: PipelineKey { .init(query: query, delay: .milliseconds(delayMs), enabled: enabled) }
}
@concurrent
func hashFileSet(matching query: String) async throws -> String { // off the main actor
var hasher = Hasher() // stand-in: per-process seeded, not a stable digest
for file in try listFiles(matching: query) {
try Task.checkCancellation() // cooperative cancel point
hasher.combine(try Data(contentsOf: file))
}
return String(hasher.finalize(), radix: 16)
}
struct SearchView: View {
@State private var model = Model()
var body: some View {
Form { /* TextField, Stepper, Toggle, result */ }
.task(id: model.key) {
let key = model.key
guard key.enabled else { model.result = nil; return }
do {
try await Task.sleep(for: key.delay) // the debounce
let digest = try await hashFileSet(matching: key.query)
guard !Task.isCancelled else { return } // lost the race
model.result = .success(digest)
} catch is CancellationError {
} catch { model.result = .failure(error) }
}
}
}Variant B: swift-async-algorithms operators. The debounce interval is a let, so changing N or the toggle restarts the consuming task:
@MainActor @Observable final class Pipeline {
@ObservationIgnored private let input = AsyncStream.makeStream(of: String.self, bufferingPolicy: .bufferingNewest(1))
@ObservationIgnored private var runner: Task<Void, Never>?
var result: String?
func queryChanged(_ q: String) { input.continuation.yield(q) }
func configure(enabled: Bool, delay: Duration) {
runner?.cancel() // cancels pending debounce + in-flight hash
runner = nil
guard enabled else { return }
let queries = input.stream
runner = Task { [weak self] in
let digests = queries
.debounce(for: delay) // interval fixed per run
.flatMapLatest { q in // AsyncAlgorithms 1.3
AsyncThrowingStream<String, Error> { c in // one-element inner sequence
let job = Task {
do { c.yield(try await hashFileSet(matching: q)); c.finish() }
catch { c.finish(throwing: error) }
}
c.onTermination = { _ in job.cancel() } // switch -> cancel the hash
}
}
do { for try await d in digests { self?.result = d } } catch {}
}
}
}WARNING
Variant B shares one AsyncStream across restarts. That is safe only because a restart cancels the old iterator before the next one is created. AsyncStream is designed for a single consumer, and the behaviour of two concurrent iterators is (unverified). The one-element inner sequence needs its own unstructured Task plus onTermination to forward cancellation into the hash: an async function cannot be the inner of flatMapLatest directly, because no mapLatest exists. Neither sketch here is compiled.
Per-event trace (Variant A).
| Event | What happens |
|---|---|
| Keystroke during debounce | model.query mutates, so Observation invalidates the body and model.key differs. SwiftUI cancels the task, and Task.sleep throws CancellationError at once (handler-driven, no polling). A new task starts a fresh full-N sleep. |
| Keystroke during hash | The same restart. The old task's flag is set, and its hash stops at the next checkCancellation() between files: at most one file's work is wasted. Cancel does not wait, so for that stretch old and new tasks run concurrently. A hash that finished just before the cancel is discarded by guard !Task.isCancelled. |
| Interval change | key.delay differs, so the task restarts: the current query is re-debounced with the new N and rehashed, even if its result is already shown. Avoiding the rehash means taking delay out of id and reading it at sleep time, after which a change no longer affects a sleep already running. |
| Toggle off | key.enabled flips, so SwiftUI cancels the running task (pending sleep or in-flight hash). The new task sees enabled == false, clears the result and returns. |
In Variant B, a keystroke during the debounce moves the element deadline, and the clock loop re-checks it on wake (Time and scheduling). A keystroke during a hash lets flatMapLatest cancel the inner task, bump the generation and drop the stale result. An interval change or toggle-off cancels runner, which tears down debounce and flatMapLatest through their cancellation handlers. A query buffered in the old debounce is lost.
Fit with a per-frame UI. .task(id:) is what sparkles needs: a restartable effect keyed on a value compared each "frame", which here means each body evaluation. An immediate-mode host can reproduce it exactly. Each frame, compute the key and compare it with the last one; if it differs, cancel the scoped fiber and spawn a new one. Neither debounce nor flatMapLatest is required. The operator form (Variant B) suits a widget tree rebuilt every frame less well: it needs a long-lived push channel into the pipeline and a full rebuild whenever a parameter changes.
Strengths
- Cancellation is part of the runtime: structured propagation,
withTaskCancellationHandlerfor wake-ups, and cancellation-awaresleep. Operators inherit it. - Back-pressure by construction. Pull plus demand-gated internal readers means no unbounded queue unless you choose
AsyncStream's.unbounded. Clockas a generic parameter, which gives virtual time with no scheduler hierarchy and a tolerance hint for coalescing wake-ups.- Latest-wins at the UI level for free through
.task(id:), which covers most search-as-you-type cases without any stream operator. - Carefully specified operators. Each has a proposal, a guide, a lock-protected state machine and marble-diagram tests.
- Observation's transactional
Observationsgives a glitch-free bridge from state into streams.
Weaknesses
- Fixed time parameters. The
debounceand_throttleintervals arelet; a runtime change means a pipeline restart that loses pending elements. - Operators spawn unstructured
Tasks and rebuild structure by hand through cancellation handlers anddeinithooks. The structure of anAsyncSequencechain is invisible to the task tree. - Cancel does not join.
flatMapLatestandTask.cancel()let cancelled CPU work overlap its replacement, and correctness depends on generation counters orisCancelledre-checks. - Small, slow-moving surface.
throttleis still underscored,flatMapLatestis "Proposed", and arities stop at 3. There is noretry,timeout,catch, or replaying share (reductionscoversscan). - No shipped test clock.
ManualClockandAsyncSequenceValidationare internal to the package's tests; users rely onswift-clocks. - No glitch-freedom across
combineLatest, and no value cell in the stream layer.
Key design decisions and trade-offs
| Decision | Rationale | Trade-off |
|---|---|---|
Pull (async next()) as the only stream protocol | Back-pressure and for await ergonomics; streams look like loops | Every push source needs a buffer (AsyncStream) or a rendezvous (AsyncChannel) |
Time-based operators generic over Clock | Testable time without a scheduler abstraction; tolerance for power efficiency | Durations fixed at construction; no "duration as a stream" |
| Debounce re-checks the deadline on wake instead of cancelling the sleep | One long-lived clock loop; no task churn per element | A wake-up per superseded deadline; latency bounded by the interval plus tolerance |
Concurrency inside operators via unstructured Task + locks | AsyncSequence gives an operator no scope of its own | Lifetime reconstructed manually (withTaskCancellationHandler, deinit hooks); harder to reason about |
flatMapLatest cancels without awaiting; generations filter stale output | Switching is immediate; no head-of-line blocking on slow cancellation | Cancelled CPU work overlaps its successor; resources freed late |
| Cooperative, sticky, non-preemptive cancellation | Cheap, predictable, safe for invariants | CPU-bound code must poll isCancelled; a non-polling loop is uncancellable |
SwiftUI .task(id:) restarts on Equatable change | Latest-wins tied to view identity and lifetime with no operators | Restart granularity is the whole task; unrelated key changes (interval) restart work |
Observation's one-shot onChange and transactional Observations | Fine-grained invalidation for view bodies; coalesced, glitch-free async bridge | Re-arming is the caller's job; the sequence form needs the iOS 26-era SDK |
Sources
- apple/swift-async-algorithms at
088f92a30c103ddc470d771f770249271066a123:README.md,Package.swift,LICENSE.txt - Debounce:
AsyncDebounceSequence.swift,DebounceStorage.swift,DebounceStateMachine.swift,Debounce.md,TestDebounce.swift - Throttle:
AsyncThrottleSequence.swift,Throttle.md, SAA-0014 - FlatMapLatest: SAA-0018,
FlatMapLatest.md,AsyncFlatMapLatestSequence.swift,FlatMapLatestStorage.swift,TestFlatMapLatest.swift - Others:
Merge.md,CombineLatest.md,Channel.md,Share.md,AsyncShareSequence.swift,Timer.md,AsyncTimerSequence.swift,Effects.md, MPSC channel - Testing:
ManualClock.swift,Validation.md,AsyncSequenceValidation/Test.swift; pointfreeco/swift-clocks on Swift Package Index,TestClockdocs - Apple documentation:
AsyncIteratorProtocol,AsyncStream,makeStream(of:bufferingPolicy:),BufferingPolicy,Task.isCancelled,Task.checkCancellation(),withTaskCancellationHandler,Clock,InstantProtocol, SwiftUItask(id:…),withObservationTracking,Observations - Swift Evolution: SE-0395 Observation
- Related: RxJS · Kotlin Flow · Rust streams · Effect-TS · Solid signals · TC39 Signals · Jetpack Compose · Concepts · Comparison · Umbrella · ZIO · Async I/O survey