Async sources, flights and boundaries
Asynchronous values travel through Ranvier as three-state Reading<'T> outcomes (Ready value, Pending, or Failed exn) rather than manual loading booleans.
A Pending or Failed read propagates automatically through dependent memos and effects (preserving ErrorOrigin) until a boundary converts it into a concrete display value.
To choose a primitive, see the primitive decision matrix.
| Read / inspection | Behavior on Ready v | Behavior on Pending | Behavior on Failed ex |
|---|---|---|---|
node.Value / let! x = node | Tracked; returns v | Links edge and suspends (NotReadyException) | Links edge and rethrows ex |
node.TryValue / let! r = tryRead node | Tracked; Ready v | Links edge; returns Pending without suspending | Links edge; returns Failed ex without throwing |
node.Peek | Untracked; returns v | Untracked; last settled value (or default) without starting a flight | Untracked; last settled value (or default) |
node.Status ([<Flags>]) | Status.None (or Status.Stale) | Includes Status.Pending (Uninitialized before first settle) | Includes Status.Error (test flags with HasFlag) |
Async sources
createAsyncSource<'T> () creates an externally settled source cell starting in Pending ||| Uninitialized. Call src.Settle value or src.Fail exn to push outcomes from callbacks, native bridges, or deterministic tests (see Testing async state):
open Ranvier
open Ranvier.CE
let wireSession (g: Graph) =
g {
let user = createAsyncSource<string> ()
let greeting =
memo {
let! name = user
return $"Hello, {name}"
}
let before = greeting.TryValue // Pending
user.Settle "Ada"
return before, greeting.TryValue // (Pending, Ready "Hello, Ada")
}
Recovery: both
SettleandFailcan be called repeatedly. A subsequentSettleclearsStatus.Error.Threading: off-thread calls marshal through
Graph.Dispatch. WithManualDispatcher, pump on the owning thread. See Streams, threading and multi-graph dispatch.No source-level equality cutoff: unlike
Signal<'T>,src.Settle valways marks direct observers dirty, even whenvequals the previously settled value.Memo cutoff: downstream
memonodes run once, cut off equal results, and let observers resolve checks cleanly.Flight reuse:
asyncMemoPhase-1 keys andAsyncSource.bindignore equal settled keys without restarting active flights.
AsyncSource.map, map2, and zip provide combinator shortcuts.
Async memos
asyncMemo (pre-CE: createAsync*, createAsyncOn*, AsyncMemo.bind*) launches a demand-driven Task<'T> or ValueTask<'T>flight on its first read and whenever its Phase-1 reactive inputs change:
open System
open System.Net.Http
open Ranvier
open Ranvier.CE
let fetchProfile (http: HttpClient) (userId: Signal<int>) =
asyncMemo {
policy FlightPolicy.CancelPrevious
debounce (TimeSpan.FromMilliseconds 150.)
let! id = userId
let! ct = asyncMemo.cancellationToken
return! http.GetStringAsync($"/api/users/{id}", ct)
}
Phase-1 reactive tracking and RAN012
Headers, tokens, and flight policies
policy fp: overridesGraphOptions.FlightPolicyfor this node.let! ct = asyncMemo.cancellationToken: supplies the flight'sCancellationToken. On .NET (net10.0), settled non-overlapping flights callCancellationTokenSource.TryReset()to reuse token sources without reallocating.let! prev = asyncMemo.previous: suppliesPrevious<'T>, whoseprev.Settled : Task<'T voption>resolves to the last published value. Initially the value isValueNone. UnderQueue, the task waits for the preceding flight's application in start order.owning: gives the synchronous prefix (before the first suspending await) a childOwnerscope (see Lifetimes), disposed when a new key starts or the node is disposed.Disposal while pending:
Disposedsettles readers once withObjectDisposedException.
FlightPolicy | Starts immediately | Cancels old ct | Discards superseded result | Applies every flight |
|---|---|---|---|---|
CancelPrevious (default) | Yes | Yes | Yes | No |
KeepLatest | Yes | No | Yes | No |
Queue | Yes | No | No | Yes, in start order |
FinishCurrent | Trailing run after current settles | No | Current finishes, then 1 trailing flight | No (stays Pending until trailing settles) |
Drop | No (ignores changes in flight) | No | Current flight stands | No |
DropWhilePending | Retries once only if flight fails after a dropped change | No | Keeps success; replaces stale failure | No |
An equal settled Phase-1 key precedes every flight policy: it neither cancels under CancelPrevious nor enqueues under Queue.
Settled-value cutoff
By default, AsyncMemo<'T> compares settled outputs with GraphOptions.Equality; supply comparer cmp in asyncMemo (or createAsyncWithComparer, createOwningAsyncWithComparer, createAsyncOnWithComparer, createOwningAsyncOnWithComparer) to override it per node:
let normalizedTag (rawQuery: Signal<string>) (lookup: string -> System.Threading.Tasks.Task<string>) =
asyncMemo {
policy FlightPolicy.KeepLatest
comparer System.StringComparer.OrdinalIgnoreCase
let! q = rawQuery
return! lookup q
}
On a direct Ready prev -> Ready next refresh, observers see no intervening Pending or Failed publication. AsyncMemo<'T> compares prevand next and suppresses downstream observer wakes when the values compare equal.
A direct refresh can happen on .NET when the task completes synchronously during launch, for example with Task.FromResult on a warm cache hit. It can also happen when an unannounced refresh settles from a Ready state.
If observers already observed Pending or Failed before Ready nextarrived, the state transition Pending -> Ready or Failed -> Ready always propagates, because readiness itself changed even when next matches an earlier value.
A comparer that throws fails the AsyncMemo<'T> with that exception.
Error and suspense boundaries
boundary catches Pending reads (pending), thrown exceptions (failed), or both, returning a Boundary<'T> (pre-CE: createSuspense*, createErrorBoundary*, createBoundary*):
| Header configuration | Pre-CE factory | Pending body | Failed body |
|---|---|---|---|
pending fallback | createSuspense | Publishes fallback last (IsWaiting = true) | Propagates Failed |
failed recover | createErrorBoundary | Propagates Pending | Publishes recover ex last (Caught = ex) |
pending + failed | createBoundary | Publishes fallback last (IsWaiting = true) | Publishes recover ex last (Caught = ex) |
Retain the last settled value
Both fallback : 'T voption -> 'T and recover : exn -> 'T voption -> 'T receive last (ValueNone before the first settled value, ValueSome prevthereafter).
Passing ValueOption.defaultValue "Loading…" shows "Loading…" initially and retains the previous settled output during later refreshes while view.IsWaitingreports true.
Tracked metadata:
view.IsWaiting,view.Caught(exnornull), andview.CaughtFrom(INodeornull) are tracked reads.Output cutoff: add
comparer cmpto customize output cutoff on settled, fallback, and recovered values.
Watch retention and recovery on the signal map
view starts at "Loading…" while the initial quote is in flight. Settle 12 publishes "Quote: 12"; Refresh (qty <- 2) keeps "Quote: 12" on screen (IsWaiting = true) while the new flight is pending; Fail quote switches to "Offline: timeout":
Example code
let desk = Desk<int>()
let qty = signal { return 1 }
let quote =
asyncMemo {
let! n = qty
return! desk.Quote n
}
let view =
boundary {
pending (ValueOption.defaultValue "Loading…")
failed (fun ex _ -> "Offline: " + ex.Message)
let! q = quote
return $"Quote: {q}"
}
effect {
let! text = view
printfn "%s" text
}
controls [
button "Settle 12" (fun () -> desk.Settle 12)
|> describe "The first quote settles: view displays Quote: 12."
|> expect "settled at Quote: 12" (fun () -> view.Peek = "Quote: 12" && not view.IsWaiting)
button "Refresh (qty <- 2)" (fun () -> qty.Value <- 2)
|> describe "A new flight starts: pending retains Quote: 12 while IsWaiting is true."
|> expect "retains Quote: 12 while waiting" (fun () -> view.Peek = "Quote: 12" && view.IsWaiting)
button "Fail quote" (fun () -> desk.Fail "timeout")
|> describe "The flight faults: failed recovers with Offline: timeout."
|> expect "recovers from failure" (fun () -> view.Peek = "Offline: timeout" && not view.IsWaiting)
]
For suspension and flight policy benchmarks, see Benchmarks → Suspension.