pysxLearn by building

Foundations · Lesson 3 of 28

Live signals and snapshots

Predict which values update after a write and which values stay fixed.

A Signal is a small piece of reactive state. Calling it reads the current value; set replaces that value and update computes a replacement from the current one. State created inside the application belongs to that session.

The most useful distinction is between passing a readable object and reading it now. A live template hole can subscribe to a Signal. A plain integer obtained from count() is just an integer, even if it originally came from a Signal.

Understand the moving parts

Create the snapshot before returning the template. The two outputs start at the same value, so initial HTML cannot prove which is reactive. Only a later write exposes the difference. This is why the exercise asks you to interact.

Keep derived work out of event handlers when it can be expressed as a readable value. Your handler should change the source; the renderer can then update every dependent location consistently. Reset is another ordinary write, not a reload.

Walk through the code

from pysx import Fragment, pysx, signal


def app(prefix: str = "") -> Fragment:
    count = signal(0)
    snapshot = count()

    def increment(_: object) -> None:
        count.update(lambda value: value + 1)

    return pysx(t"""
        button(id={prefix + "increment"} onClick={increment}): "Increment"
        output(id={prefix + "live-count"}): {count}
        p: "Snapshot: "
        output(id={prefix + "snapshot-count"}): {snapshot}
    """)

snapshot stores the initial integer, while the count hole stays live. Increment writes only count, so two clicks produce live 2 and snapshot 0.

Try it live

Increment twice, read both outputs, and reset. Try the same steps in another tab.

What to observe

Live reaches 2 while snapshot remains 0. Reset returns live to 0 without navigation.

0

Snapshot:

0

Take this with you

An uncalled readable stays live; an eager read is a snapshot.