Skip to content

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 / inspectionBehavior on Ready vBehavior on PendingBehavior on Failed ex
node.Value / let! x = nodeTracked; returns vLinks edge and suspends (NotReadyException)Links edge and rethrows ex
node.TryValue / let! r = tryRead nodeTracked; Ready vLinks edge; returns Pending without suspendingLinks edge; returns Failed ex without throwing
node.PeekUntracked; returns vUntracked; last settled value (or default) without starting a flightUntracked; 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 Settle and Fail can be called repeatedly. A subsequent Settle clears Status.Error.

  • Threading: off-thread calls marshal through Graph.Dispatch. With ManualDispatcher, 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 when v equals the previously settled value.

  • Memo cutoff: downstream memo nodes run once, cut off equal results, and let observers resolve checks cleanly.

  • Flight reuse: asyncMemo Phase-1 keys and AsyncSource.bind ignore 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: overrides GraphOptions.FlightPolicy for this node.

  • let! ct = asyncMemo.cancellationToken: supplies the flight's CancellationToken. On .NET (net10.0), settled non-overlapping flights call CancellationTokenSource.TryReset() to reuse token sources without reallocating.

  • let! prev = asyncMemo.previous: supplies Previous<'T>, whose prev.Settled : Task<'T voption> resolves to the last published value. Initially the value is ValueNone. Under Queue, the task waits for the preceding flight's application in start order.

  • owning: gives the synchronous prefix (before the first suspending await) a child Owner scope (see Lifetimes), disposed when a new key starts or the node is disposed.

  • Disposal while pending: Disposed settles readers once with ObjectDisposedException.

FlightPolicyStarts immediatelyCancels old ctDiscards superseded resultApplies every flight
CancelPrevious (default)YesYesYesNo
KeepLatestYesNoYesNo
QueueYesNoNoYes, in start order
FinishCurrentTrailing run after current settlesNoCurrent finishes, then 1 trailing flightNo (stays Pending until trailing settles)
DropNo (ignores changes in flight)NoCurrent flight standsNo
DropWhilePendingRetries once only if flight fails after a dropped changeNoKeeps success; replaces stale failureNo

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 configurationPre-CE factoryPending bodyFailed body
pending fallbackcreateSuspensePublishes fallback last (IsWaiting = true)Propagates Failed
failed recovercreateErrorBoundaryPropagates PendingPublishes recover ex last (Caught = ex)
pending + failedcreateBoundaryPublishes 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 (exn or null), and view.CaughtFrom (INode or null) are tracked reads.

  • Output cutoff: add comparer cmp to 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)
]
Hover a node for its state; click it for why it last ran.

For suspension and flight policy benchmarks, see Benchmarks → Suspension.

Edit this page