reactive

package
v0.0.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 11, 2026 License: Apache-2.0 Imports: 7 Imported by: 0

README

Reactive graph

github.com/moriyoshi/gpui-go/reactive implements synchronous, owner-scoped signals, memos and effects. It follows Solid's fine-grained dependency tracking: computations subscribe to the values they read, and replace those dependencies on each evaluation. It has no GPUI, cgo, display or template dependency.

graph := reactive.NewGraph()
defer graph.Dispose()
owner := graph.Root()
count := reactive.NewSignal(owner, 0)
parity := reactive.NewMemo(owner, func() string {
    if count.Get()%2 == 0 { return "even" }
    return "odd"
})
effect, err := reactive.NewEffect(owner, func(run *reactive.Scope) error {
    fmt.Println(parity.Get())
    run.OnCleanup(func() { /* release this evaluation's resources */ })
    return nil
})
if err != nil { return err }
_ = effect // Explicit Dispose is optional when its owner is disposed.
err = graph.Batch(func() error {
    if err := count.Set(1); err != nil { return err }
    return count.Set(2)
})
// The memo recalculates once; the effect does not rerun because parity is equal.

Signal.Get tracks reads; Peek reads without subscribing. Set and Update propagate synchronously outside a batch. NewMemo calculates its initial value immediately and caches subsequent results. Reading a stale memo inside a batch pulls its current value. Memo dependencies update before dependent effects, so diamond graphs do not expose intermediate derived values. Memo.Peek returns the cached value without refreshing it.

The default equality is reflect.DeepEqual. Supply a typed equality function as the optional last constructor argument, or explicit nil to always notify. Treat values as immutable: mutating a referenced slice, map or pointer in place cannot reliably detect a change. Use a new value with Set.

Graph.Batch nests and delays effects and settled callbacks until the outer batch returns. Values change immediately; errors do not roll back writes. Graph.Untrack and generic reactive.Untrack suppress dependency collection for a callback. Keep memo calculations pure; ordinary signal writes inside a tracked memo return ErrMemoWrite.

Every computation has an owner Scope. Scope.Child creates a nested lifetime; OnCleanup releases resources on disposal without collecting dependencies. Effects receive a fresh run scope whose children and cleanups are disposed before reevaluation. Put nested effects in that run scope when their lifetime follows an evaluation. Scope.Dispose, Effect.Dispose and Graph.Dispose are idempotent. Signals can outlive their original scope; disposed observers are unsubscribed, and writes after graph disposal fail.

Graph.OnSettled installs an ordered sink after successful stabilization and returns its removal function. Sinks cannot write signals. Failed computations block sinks until recovery; cycles and effects exceeding 1,000 executions per flush report errors. Computation panics become errors, and tracking is restored. Graph.Flush explicitly propagates pending work, and Stats exposes computation/dependency/queue counts for diagnostics.

A graph belongs to one goroutine. Send background results to the application event loop before setting signals. Graphs have separate tracking contexts: reading another graph's signal does not create a dependency. Async resources, concurrent scheduling, proxies/stores, transitions, hydration and a browser DOM are outside this package. See the GPUI node binding for rendering.

Documentation

Overview

Package reactive implements an owner-scoped, synchronous signal graph. A graph belongs to one goroutine. Components build once; computations track only the signals/memos read during their current evaluation.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrDisposed   = errors.New("reactive: graph or owner is disposed")
	ErrCycle      = errors.New("reactive: cyclic computation")
	ErrRunaway    = errors.New("reactive: effect exceeded 1000 executions in one flush")
	ErrMemoWrite  = errors.New("reactive: memo calculations cannot write signals")
	ErrFlushWrite = errors.New("reactive: settled callbacks cannot write reactive state")
)

Functions

func Untrack

func Untrack[T any](scope *Scope, fn func() T) T

Types

type Effect

type Effect struct {
	// contains filtered or unexported fields
}

Effect reruns after dependencies change. Each evaluation gets a fresh child scope whose cleanup runs before reevaluation. The initial run is synchronous unless created inside a batch or another running computation.

func NewEffect

func NewEffect(owner *Scope, fn func(*Scope) error) (*Effect, error)

func (*Effect) Dispose

func (e *Effect) Dispose()

type Graph

type Graph struct {
	// contains filtered or unexported fields
}

func NewGraph

func NewGraph() *Graph

func (*Graph) Batch

func (g *Graph) Batch(fn func() error) (err error)

Batch groups writes. Values change immediately; effects and settled callbacks run after the outer batch. Reads of stale memos update them on demand. Errors do not roll back writes which have already happened.

func (*Graph) Dispose

func (g *Graph) Dispose()

func (*Graph) Flush

func (g *Graph) Flush() error

func (*Graph) OnSettled

func (g *Graph) OnSettled(fn func() error) func()

OnSettled registers a render sink invoked after computations stabilize. The callback must not write signals. Remove the callback when its sink is closed.

func (*Graph) Root

func (g *Graph) Root() *Scope

func (*Graph) Stats

func (g *Graph) Stats() Stats

func (*Graph) Untrack

func (g *Graph) Untrack(fn func())

type Memo

type Memo[T any] struct {
	// contains filtered or unexported fields
}

Memo caches a pure derived value. Downstream computations observe its value version, so equal results suppress effects even when source signals changed.

func NewMemo

func NewMemo[T any](owner *Scope, fn func() T, equal ...func(T, T) bool) *Memo[T]

func (*Memo[T]) Get

func (m *Memo[T]) Get() T

func (*Memo[T]) Peek

func (m *Memo[T]) Peek() T

type Scope

type Scope struct {
	// contains filtered or unexported fields
}

Scope owns computations, nested scopes and cleanup callbacks. Disposing an owner unsubscribes effects and releases children in reverse creation order.

func (*Scope) Child

func (s *Scope) Child() *Scope

func (*Scope) Dispose

func (s *Scope) Dispose()

func (*Scope) Disposed

func (s *Scope) Disposed() bool

func (*Scope) Graph

func (s *Scope) Graph() *Graph

func (*Scope) OnCleanup

func (s *Scope) OnCleanup(fn func())

type Signal

type Signal[T any] struct {
	// contains filtered or unexported fields
}

Signal is an immutable-by-convention value cell. The default equality uses reflect.DeepEqual; pass an equality function, or nil to always notify. Existing signal values can outlive an owner; disposed computations no longer observe it.

func NewSignal

func NewSignal[T any](owner *Scope, initial T, equal ...func(T, T) bool) *Signal[T]

func (*Signal[T]) Get

func (s *Signal[T]) Get() T

func (*Signal[T]) Peek

func (s *Signal[T]) Peek() T

func (*Signal[T]) Set

func (s *Signal[T]) Set(value T) error

func (*Signal[T]) Update

func (s *Signal[T]) Update(fn func(T) T) error

type Stats

type Stats struct{ Computations, Dependencies, Pending int }

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL