Skip to content

Lifetimes

Every derived or side-effecting node (Memo, MemoTable, Effect, Boundary, AsyncMemo, StreamMemo, Timed, Projection, Lookup) attaches at construction to Graph.CurrentOwner. Disposing a Graph tears down graph.Root and every child scope under it in O(nodes)O(\text{nodes}) time.

Root input cells — Signal<'T>, ReadOnlySignal<'T>, SignalPort<'T>, and AsyncSource<'T> — hold no Owner and are collected by the GC once unreferenced.

Activating a graph

Scope helpers (root, scope { ... }, cleanup, getOwner ()) resolve Graph.Current, whereas source-bound derivations (memo, effect, boundary, asyncMemo, stream) infer source.Graphdirectly from their Phase-1 let! / and! inputs and attach to source.Graph.CurrentOwner.

See The graph for full details on:

Roots and owners

Create a disposable child Owner scope in O(1)O(1) inside an active graph with root { ... } (createRoot):

  • Unit body returns Owner: a unit body returns the newly created Owner directly (use scope = root { ... }).

  • Custom return value (root.owner): bind let! o = root.owner and end with return (o, result) when setup returns domain handles alongside the scope.

  • Re-entering a captured owner (scope { ... }): any scope: Owner is itself a 0 B computation expression builder (scope { ... }, wrapping runWithOwner scope) that attaches new nodes or cleanups to scope. Because Owner stores no back-reference to Graph, ensure its graph is active when re-entering outside a turn (graph { scope { ... } }).

  • Inspecting the current owner: call getOwner () inside an owning scope, or tryGetOwner () (Owner voption) when helper code may also run inside a pure memo (where tryGetOwner () returns ValueNone without throwing).

  • Attaching external disposables: call scope.Attach disposable to dispose any IDisposable resource automatically with scope.

open Ranvier
open Ranvier.CE

let mountPage (graph: Graph) (route: Signal<string>) =
    graph {
        return
            root {
                let! owner = root.owner
                let title = memo { let! r = route in return $"Page: {r}" }
                effect { let! t = title in printfn "%s" t }
                return owner, title
            }
    }

Disposing an owner

Disposing an Owner tears down its entire subtree in O(subtree)O(\text{subtree}) time, unlinking every upstream observer edge1 so subsequent signal writes never wake disposed effects.2 Disposal is idempotent:3

Example code
let count = signal { return 0 }
let mutable runs = 0
let scope =
    root {
        effect {
            let! n = count
            runs <- runs + 1
            printfn "count = %d" n
        }
    }

controls [
    button "Write 1" (fun () -> count.Value <- 1)
    |> describe "The root's effect responds while its owner is alive."
    |> expect "Effect runs before disposal" (fun () -> runs = 2)
    button "Dispose root" (fun () -> scope.Dispose ())
    |> describe "Disposal detaches the effect from count."
    |> expect "Disposal does not re-run the effect" (fun () -> runs = 2)
    button "Write 2" (fun () -> count.Value <- 2)
    |> describe "count updates, while the disposed effect stays silent."
    |> expect "Disposed effect never runs again" (fun () -> runs = 2 && count.Peek = 2)
]
Hover a node for its state; click it for why it last ran.

A disposed Memo<'T> detaches its upstream sources and stops recomputing, while answering reads with its last cached value.4 When cached payloads themselves must be freed on eviction or disposal, use a MemoTable<'K, 'V>.

Cleanup

Register teardown logic on the innermost active scope with cleanup { ... }(onCleanup f) in O(1)O(1).

Inside an effect, boundary, or memo { owning; ... }, each registered cleanup runs untracked before the next re-run and on scope disposal, executing at most once:5

Example code
let user = signal { return "Ada" }
let mutable released = []
let scope =
    root {
        effect {
            let! name = user
            printfn "subscribe %s" name
            cleanup {
                released <- released @ [ name ]
                printfn "unsubscribe %s" name
            }
        }
    }

controls [
    button "Switch to Grace" (fun () -> user.Value <- "Grace")
    |> describe "Ada's cleanup runs before subscribing to Grace."
    |> expect "Previous subscription released" (fun () -> released = [ "Ada" ])
    button "Dispose" (fun () -> scope.Dispose ())
    |> describe "Disposal releases Grace and detaches the effect."
    |> expect "Final subscription released" (fun () -> released = [ "Ada"; "Grace" ])
]
Hover a node for its state; click it for why it last ran.

Ordering, purity, and error containment

  • LIFO interleaving: cleanups and child scopes share one reverse-acquisition stack:6 a cleanup registered after a child node runs before that child is disposed.

  • Pure scope guard: calling cleanup inside a pure memo raises InvalidOperationException.7 Add the owning header (memo { owning; ... }) when a derived computation owns resources.

  • Fault isolation: a throwing cleanup records its exception in scope.Errors (or graph.Root.Errors for computation scopes; inspect new entries via scope.ErrorCount and scope.ErrorsFrom idx) while remaining cleanups still run.8

  • Writes during cleanup: signal writes inside a cleanup are visible to the incoming re-run without scheduling a duplicate run.9

See Benchmarks → Lifetimes for creation and teardown instruction counts.

Edit this page