Programming Search⌘K

Conceptcore

Reactive programming

Also called dataflow programming, signals, observables, functional reactive programming, FRP, reactive streams, spreadsheet model.

Reactive programming states how values depend on each other, as cells in a spreadsheet do, and a runtime updates the dependent values or streams when their inputs change.

Applies to
core-languages

Idea

Reactive programming states how values depend on each other, and lets a runtime keep the dependent values up to date when their inputs change. A spreadsheet is the common example: a cell holds a formula such as =A1*B1, and when A1 changes, the cell changes too, with no code to update it. Dataflow programming is the wider idea: a program is a graph of operations, and data flows along the edges, so each operation runs when its inputs are ready. The example below gives signals to Python. A computed signal records which signals it reads, and it computes again only when one of them has changed and someone reads it:

class Signal:
    current = None  # the computed signal that is being evaluated now

    def __init__(self, value=None, compute=None):
        self.value, self.compute = value, compute
        self.dirty = compute is not None
        self.dependents = set()

    def get(self):
        if Signal.current is not None:
            self.dependents.add(Signal.current)  # record who read this signal
        if self.dirty:
            outer, Signal.current = Signal.current, self
            try:
                self.value = self.compute()
            finally:
                Signal.current = outer
            self.dirty = False
        return self.value

    def set(self, value):
        self.value = value
        for d in list(self.dependents):
            d.invalidate()

    def invalidate(self):
        if not self.dirty:
            self.dirty = True
            for d in list(self.dependents):
                d.invalidate()


log = []


def computed(name, fn):
    def run():
        log.append(name)
        return fn()

    return Signal(compute=run)


price, qty, shipping = Signal(10), Signal(3), Signal(5)
subtotal = computed("subtotal", lambda: price.get() * qty.get())
total = computed("total", lambda: subtotal.get() + shipping.get())

print(total.get(), log)
qty.set(4)
shipping.set(0)
print(total.get(), log[2:])
print(total.get(), log[4:])
Output
35 ['total', 'subtotal']
40 ['total', 'subtotal']
40 []

Nothing in the code tells total to update when qty changes. total read subtotal, which read qty, so the runtime knows the chain. Two changes in a row cost only one computation of each formula, because a change only marks the computed values as dirty, and the work happens when total is read. A read with no change costs no computation at all.

How it works

The dependency graph. A reactive program is a directed graph. Sources, such as input fields, sensors or state signals, are the roots. Derived values and effects, such as computed signals, rendered views and writes to the screen, are the other nodes. An edge goes from each value to each value that uses it. A change at a source must reach every node that depends on it, and only those.

Automatic dependency tracking. Many systems find the edges at run time. While a computed value runs, the runtime records each signal it reads, as Signal.current does in the example. The TC39 proposal for signals in JavaScript describes the same method: "Computed Signals work by automatically tracking which other Signals are read during their evaluation."1 Because the edges come from the actual reads, a value that reads a only in one branch of an if depends on a only when that branch runs.

Push, pull and glitches. A change can be pushed: the source calls its dependents at once. Or it can be pulled: the dependents compute only when read. Pure push has a problem in graphs shaped like a diamond. If d depends on b and c, and both depend on a, then a push from a can update d after b changes and before c does. The value of d in between is a glitch, a state that never existed. The wrong block in the Python file shows one. Systems avoid glitches by updating in topological order, or by the push-pull method of the example: push a dirty mark, then pull the values. The signals proposal calls this a "push-pull" construction and requires that computation is "glitch-free".1

Streams of events. A second family treats events over time as a collection. ReactiveX describes itself as "a library for composing asynchronous and event-based programs by using observable sequences", which "extends the observer pattern to support sequences of data and/or events".2 An observable is like a list that arrives over time, and operators such as map, filter, scan, merge and debounce make new observables from old ones, the way higher-order functions make new lists.

Back-pressure. When a producer is faster than a consumer, the items must wait somewhere, and an unbounded buffer can use all memory. Reactive Streams is "an initiative to provide a standard for asynchronous stream processing with non-blocking back pressure."3 A subscriber states how many items it can take, and the publisher sends no more than that. Java put these interfaces in its standard library as java.util.concurrent.Flow, which the Java file of this page uses.

In languages

LanguageVerdictNote
PythonIdiom
C++Idiom
JavaStandard library
CAbsent
C#Standard library
JavaScriptIdiom
TypeScriptIdiomAs JavaScript; RxJS and signal libraries have full type definitions.
GoIdiom
RustIdiom
KotlinLibraryFlow and StateFlow in kotlinx.coroutines give reactive streams, and Compose recomposes the user interface when state changes; no example file because kotlinc is not installed on the machine that recorded the examples.
SQLIdiomA view is a query over tables that is computed again when read; some engines keep materialized views up to date as the tables change.
BashIdiomA pipeline such as tail -f, grep and awk is a dataflow graph in which each process reacts to lines as they arrive.
PowerShellIdiomThe pipeline streams objects through cmdlets one at a time; no example file because pwsh is not installed on the machine that recorded the examples.
HTMLDoes not applyHTML has no derived values; scripts and frameworks bind data to elements.
CSSIdiomCustom properties, calc() and media queries are relations that the browser computes again when their inputs change.
Regular expressionsDoes not applyRegular expressions have no values that change over time.
Language Verdict Mechanism
Python idiom closures and generators; RxPY
JavaScript idiom Proxy, events; RxJS and signal libraries
TypeScript idiom as JavaScript
Java stdlib java.util.concurrent.Flow, SubmissionPublisher; Reactor, RxJava
Kotlin library Flow and StateFlow in kotlinx.coroutines
C# stdlib IObservable<T> and IObserver<T>; Rx.NET for operators
Go idiom goroutines connected by channels
Rust idiom iterators; Rc<RefCell<T>> with callbacks; stream crates
C absent a table of formulas in topological order
C++ idiom lazy range adaptors; RxCpp, Qt properties
Bash idiom pipelines of processes
PowerShell idiom the object pipeline
SQL idiom views and materialized views
Regex n/a no values that change
HTML n/a no derived values
CSS idiom custom properties and calc()

No core language has reactive values in its syntax. Java and C# have the interfaces of reactive streams in the standard library, and leave the operators to libraries. In JavaScript, reactive programming is mostly the work of user interface frameworks. React computes the view again from state, Vue tracks reads through proxies as in the JavaScript file, and Solid, Svelte, Angular and Preact use signals. The signals proposal aims to give these frameworks one shared base.

Dataflow without reactivity is more common. Go programs connect goroutines with channels into pipelines in which every stage runs at the same time. Iterators in Rust, ranges in C++, streams in Java and generators in Python are pull-based pipelines: each stage asks the one before it for the next value. Unix pipelines connect processes in the same way, and the operating system gives them back-pressure through the fixed size of the pipe buffer.

PythonGitHub
class Observable:
    def __init__(self, subscribe):
        self.subscribe = subscribe

    def map(self, f):
        return Observable(lambda emit: self.subscribe(lambda x: emit(f(x))))

    def filter(self, keep):
        return Observable(lambda emit: self.subscribe(lambda x: keep(x) and emit(x)))

    def scan(self, f, acc):
        def subscribe(emit):
            state = [acc]

            def step(x):
                state[0] = f(state[0], x)
                emit(state[0])

            self.subscribe(step)

        return Observable(subscribe)


def readings(emit):
    for t in [18, 22, 19, 25, 30]:
        emit(t)


hot = Observable(readings).filter(lambda t: t > 20)
hot.map(lambda t: f"hot {t}").subscribe(print)
hot.scan(lambda total, t: total + t, 0).subscribe(lambda s: print("running sum", s))
Output
hot 22
hot 25
hot 30
running sum 22
running sum 47
running sum 77

This code runs but gives a wrong answer on purpose.

class Cell:
    def __init__(self, value):
        self.value, self.observers = value, []

    def set(self, value):
        self.value = value
        for notify in self.observers:
            notify()


a = Cell(1)
b = Cell(a.value * 2)
c = Cell(a.value + 1)
d = Cell(b.value + c.value)
a.observers += [lambda: b.set(a.value * 2), lambda: c.set(a.value + 1)]
b.observers.append(lambda: d.set(b.value + c.value))
c.observers.append(lambda: d.set(b.value + c.value))
d.observers.append(lambda: print("d =", d.value))

a.set(10)
Output
d = 22
d = 31
  • Verdict: idiom. Python has no observables or signals in the standard library. A few lines of closures give an observable with map, filter and scan, and the first block of this page gives signals with automatic dependency tracking. Libraries such as RxPY give the full ReactiveX operators.
  • Each call to subscribe runs the source again, so the readings are produced twice, once for each subscriber. This is a cold observable. A hot observable shares one run of the source among all subscribers.
  • The wrong block pushes each change at once. When a changes, b updates and pushes to d before c has updated, so d shows 22, a value that matches no consistent state: the right value is 31. This is a glitch. Engines avoid it by updating in topological order, or by marking values as dirty and computing them when read, as the first block of the page does.
#include <iostream>
#include <ranges>
#include <vector>

int main() {
    std::vector<int> readings{18, 22, 19, 25, 30, 12, 40};
    int tested = 0;
    auto hot = readings
        | std::views::filter([&](int t) { ++tested; return t > 20; })
        | std::views::transform([](int t) { return t * 9 / 5 + 32; });

    std::cout << "tested before use: " << tested << "\n";
    for (int f : hot | std::views::take(2)) std::cout << f << " F\n";
    std::cout << "tested: " << tested << "\n";
}
Output
tested before use: 0
71 F
77 F
tested: 5
  • Verdict: idiom. Range adaptors build a lazy, pull-based dataflow pipeline: no element is tested until the loop asks for one, and the loop stops after two results, so the last two readings are never tested. The count is 5 and not 4, because take moves the inner iterator one step past the second result before it stops. C++ has no push-based observables in the standard library. RxCpp and Qt's signals and properties give reactive programming in libraries.
JavaGitHub
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Flow;
import java.util.concurrent.SubmissionPublisher;

public class Main {
    public static void main(String[] args) throws Exception {
        CountDownLatch done = new CountDownLatch(1);
        try (SubmissionPublisher<Integer> readings = new SubmissionPublisher<>()) {
            readings.subscribe(new Flow.Subscriber<>() {
                Flow.Subscription subscription;
                int sum;

                public void onSubscribe(Flow.Subscription s) {
                    subscription = s;
                    s.request(1);
                }

                public void onNext(Integer t) {
                    if (t > 20) {
                        sum += t;
                        System.out.println("hot " + t + ", running sum " + sum);
                    }
                    subscription.request(1); // ask for one more item: back-pressure
                }

                public void onError(Throwable e) {
                    e.printStackTrace();
                }

                public void onComplete() {
                    System.out.println("done");
                    done.countDown();
                }
            });
            for (int t : new int[] {18, 22, 19, 25, 30}) {
                readings.submit(t);
            }
        }
        done.await();
    }
}
Output
hot 22, running sum 22
hot 25, running sum 47
hot 30, running sum 77
done
  • Verdict: stdlib. java.util.concurrent.Flow defines the four interfaces of the Reactive Streams standard: publisher, subscriber, subscription and processor. SubmissionPublisher delivers items on a thread pool. The subscriber asks for items with request, so a slow subscriber is never sent more than it asked for. Libraries such as Reactor and RxJava give the operators.
#include <stdio.h>

enum { PRICE, QTY, SHIPPING, SUBTOTAL, TOTAL, N };
static double cell[N];
static int recomputed;

static double subtotal(void) { return cell[PRICE] * cell[QTY]; }
static double total(void) { return cell[SUBTOTAL] + cell[SHIPPING]; }

/* Formulas in topological order: each one reads only cells set before it. */
static const struct {
    int target;
    double (*fn)(void);
} formulas[] = { { SUBTOTAL, subtotal }, { TOTAL, total } };

static void set(int c, double v)
{
    cell[c] = v;
    for (size_t i = 0; i < sizeof formulas / sizeof formulas[0]; i++) {
        cell[formulas[i].target] = formulas[i].fn();
        recomputed++;
    }
}

int main(void)
{
    set(PRICE, 10);
    set(QTY, 3);
    set(SHIPPING, 5);
    printf("total %.0f\n", cell[TOTAL]);
    set(QTY, 4);
    printf("total %.0f after %d recomputations\n", cell[TOTAL], recomputed);
    return 0;
}
Output
total 35
total 45 after 8 recomputations
  • Verdict: absent. C has no events or closures to build observers from. A table of formulas in topological order makes a small spreadsheet: after each change, the program computes every formula once, in an order where each formula reads only values that are already up to date. This avoids glitches, but it recomputes all formulas, even those that the change does not affect.
var sensor = new Sensor();
var sum = 0;
using var subscription = sensor.Where(t => t > 20).Subscribe(new Observer<int>(
    t => Console.WriteLine($"hot {t}, running sum {sum += t}"),
    () => Console.WriteLine("done")));

foreach (var t in new[] { 18, 22, 19, 25, 30 }) sensor.Publish(t);
sensor.Complete();

class Sensor : IObservable<int>
{
    readonly List<IObserver<int>> observers = new();

    public IDisposable Subscribe(IObserver<int> o)
    {
        observers.Add(o);
        return new Unsubscriber(() => observers.Remove(o));
    }

    public void Publish(int t) { foreach (var o in observers.ToList()) o.OnNext(t); }
    public void Complete() { foreach (var o in observers.ToList()) o.OnCompleted(); }
}

static class Operators
{
    public static IObservable<T> Where<T>(this IObservable<T> source, Func<T, bool> keep) =>
        new AnonymousObservable<T>(o => source.Subscribe(new Observer<T>(x => { if (keep(x)) o.OnNext(x); }, o.OnCompleted)));
}

class AnonymousObservable<T>(Func<IObserver<T>, IDisposable> subscribe) : IObservable<T>
{
    public IDisposable Subscribe(IObserver<T> o) => subscribe(o);
}

class Observer<T>(Action<T> next, Action completed) : IObserver<T>
{
    public void OnNext(T value) => next(value);
    public void OnCompleted() => completed();
    public void OnError(Exception e) => throw e;
}

class Unsubscriber(Action onDispose) : IDisposable
{
    public void Dispose() => onDispose();
}
Output
hot 22, running sum 22
hot 25, running sum 47
hot 30, running sum 77
done
  • Verdict: stdlib. The interfaces IObservable<T> and IObserver<T> are in the System namespace of the base library, but the operators are not. Reactive Extensions for .NET (Rx.NET) gives Where, Select, Throttle and many more, and LINQ query syntax works on observables. The Where here is a small version of the Rx operator.
JavaScriptGitHub
let active = null;
const deps = new Map(); // property name -> set of effects that read it

function reactive(obj) {
  return new Proxy(obj, {
    get(target, key) {
      if (active) {
        if (!deps.has(key)) deps.set(key, new Set());
        deps.get(key).add(active);
      }
      return target[key];
    },
    set(target, key, value) {
      target[key] = value;
      for (const effect of deps.get(key) ?? []) effect();
      return true;
    },
  });
}

function effect(fn) {
  active = fn;
  fn();
  active = null;
}

const cart = reactive({ price: 10, qty: 3, note: "" });
effect(() => console.log(`total ${cart.price * cart.qty}`));
cart.qty = 4;
cart.price = 12;
cart.note = "gift"; // no effect read note, so nothing runs
Output
total 30
total 40
total 48
  • Verdict: idiom. JavaScript has events and promises but no signals or observables in the language. The Proxy records which effect reads which property, and a write runs the effects that depend on it. Vue works this way. RxJS gives observables, and a proposal for signals in the language is under discussion at TC39.
  • This sketch keys the dependencies by property name only, so two reactive objects with the same property names would share them. Real libraries key by object and property.
package main

import "fmt"

func source(values ...int) <-chan int {
	out := make(chan int)
	go func() {
		defer close(out)
		for _, v := range values {
			out <- v
		}
	}()
	return out
}

func filter(in <-chan int, keep func(int) bool) <-chan int {
	out := make(chan int)
	go func() {
		defer close(out)
		for v := range in {
			if keep(v) {
				out <- v
			}
		}
	}()
	return out
}

func runningSum(in <-chan int) <-chan [2]int {
	out := make(chan [2]int)
	go func() {
		defer close(out)
		sum := 0
		for v := range in {
			sum += v
			out <- [2]int{v, sum}
		}
	}()
	return out
}

func main() {
	hot := filter(source(18, 22, 19, 25, 30), func(t int) bool { return t > 20 })
	for r := range runningSum(hot) {
		fmt.Printf("hot %d, running sum %d\n", r[0], r[1])
	}
}
Output
hot 22, running sum 22
hot 25, running sum 47
hot 30, running sum 77
  • Verdict: idiom. Each stage is a goroutine that reads one channel and writes another, so the program is a dataflow graph. The stages run at the same time, and an unbuffered channel gives back-pressure: a stage waits until the next one takes its value. Closing a channel is the signal that the stream is complete.
RustGitHub
use std::cell::RefCell;
use std::rc::Rc;

struct Signal<T> {
    value: RefCell<T>,
    subscribers: RefCell<Vec<Box<dyn Fn(&T)>>>,
}

impl<T: Clone + 'static> Signal<T> {
    fn new(value: T) -> Rc<Self> {
        Rc::new(Signal { value: RefCell::new(value), subscribers: RefCell::new(Vec::new()) })
    }

    fn get(&self) -> T {
        self.value.borrow().clone()
    }

    fn set(&self, v: T) {
        *self.value.borrow_mut() = v.clone();
        for s in self.subscribers.borrow().iter() {
            s(&v);
        }
    }

    fn subscribe(&self, f: impl Fn(&T) + 'static) {
        self.subscribers.borrow_mut().push(Box::new(f));
    }

    fn map<U: Clone + 'static>(self: &Rc<Self>, f: impl Fn(&T) -> U + 'static) -> Rc<Signal<U>> {
        let out = Signal::new(f(&self.get()));
        let target = Rc::clone(&out);
        self.subscribe(move |v| target.set(f(v)));
        out
    }
}

fn main() {
    let celsius = Signal::new(20.0_f64);
    let fahrenheit = celsius.map(|c| c * 9.0 / 5.0 + 32.0);
    let label = fahrenheit.map(|f| format!("{f:.1} F"));
    label.subscribe(|s| println!("display: {s}"));

    println!("start: {}", label.get());
    celsius.set(25.0);
    celsius.set(-40.0);
}
Output
start: 68.0 F
display: 77.0 F
display: -40.0 F
  • Verdict: idiom. The standard library has no observables or signals. Iterators are pull-based dataflow, and Rc with RefCell lets callbacks share a value on one thread, as here. A subscriber that calls set on the same signal would panic, because subscribers is already borrowed. Crates such as futures give streams, and user interface crates such as Leptos and Dioxus give signals.
  • Spreadsheets. The most used reactive system. Cells form a dependency graph, and the program recomputes the cells that a change affects.
  • Functional reactive programming (FRP). Conal Elliott and Paul Hudak defined behaviors, values that vary over continuous time, and events, values at discrete times, as first-class values in Haskell. See functional programming.
  • Observables and Rx. Push-based streams of events with a rich set of operators.
  • Signals. Single values that change over time, with automatic dependency tracking and lazy computation.
  • Dataflow languages. Visual languages such as LabVIEW and Max, and stream languages such as Lustre for control systems, write programs as graphs of operations.
  • Synchronous languages. Esterel and Lustre assume that each reaction takes no time, which lets a compiler check timing for embedded systems.
  • Incremental computation. Build systems and compilers keep a graph of derived results and compute again only what a change affects.
  • Event-driven programming. Reactive systems usually run on an event loop. See event-driven programming.
  • Laziness. Pull-based dataflow computes values only when asked. See laziness.

Pitfalls

  • Glitches. Pushing changes one by one through a diamond-shaped graph can show values that never existed together. The wrong block in the Python file shows one. Use a library that updates in topological order.
  • Cycles. A value that depends on itself, directly or through others, has no fixed meaning, and a naive runtime loops forever. Most libraries detect cycles and throw an error.
  • Effects that write signals. An effect that writes to a signal that it also reads runs again and again. Keep effects at the edges of the graph, and derive values with computed signals instead.
  • Leaked subscriptions. A subscriber that never unsubscribes stays in the source's list, with all that its closure holds. Dispose of subscriptions when their owner goes away. See memory leaks.
  • Cold and hot observables. Each subscription to a cold observable runs the source again, which can repeat a network request. Share a single run when more than one subscriber needs it.
  • Hidden control flow. A change can start a long chain of updates in code far away. Stack traces show the runtime, not the cause, and debugging needs tools that show the graph.

Cost

A reactive runtime adds memory for the graph: each derived value keeps a list of its sources and a list of its dependents, and automatic tracking rebuilds the lists of a value each time it computes. A change costs time in proportion to the number of nodes it reaches, not the size of the program, which is the main gain over computing the whole view again. Lazy evaluation adds a check of the dirty flag on each read but skips work that no one reads. Stream operators cost an allocation and a function call for each item at each stage, which matters at millions of items per second, and libraries reduce it by fusing operators. Channel pipelines in Go cost a synchronization for each item at each stage, so programs send batches when items are small.

History

Dataflow ideas came from hardware and from spreadsheets. Dataflow machines were research topics at MIT and Manchester in the 1970s. Dan Bricklin and Bob Frankston released VisiCalc in 1979, the first spreadsheet for personal computers, and made reactive recalculation familiar to millions of users. Synchronous dataflow languages for control systems, Lustre and Esterel, came from France in the 1980s. Conal Elliott and Paul Hudak published "Functional Reactive Animation" at ICFP in 1997, which started functional reactive programming. Erik Meijer and his team at Microsoft built Reactive Extensions for .NET around 2009, and ports such as RxJava and RxJS followed. The Reactive Streams standard came in 2015, and Java 9 added its interfaces as java.util.concurrent.Flow in 2017. Knockout and later Vue, Solid, Svelte, Angular and Preact made signals the base of user interface frameworks in JavaScript, and a proposal to add signals to the language was presented to TC39 in 2024.

References

  1. JavaScript Signals standard proposal, TC39, Computed Signals; FAQ on push and pull
  2. ReactiveX Introduction, ReactiveX
  3. Reactive Streams, introduction

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/R0DNQJ/text.yaml