pysxLearn by building

Compose an interface · Lesson 12 of 28

Effects and component ownership

Observe changes and prove that cleanup ends an owned subscription.

An effect runs when the dependencies it read change. It is useful for work that must happen because state changed, rather than for computing another value. Return cleanup from an effect to release the previous run's resources.

Server setup, browser mount and disposal are different moments. Setup can happen before a browser attaches. A DOM command needs a mounted capability. Cleanup must still run when a branch leaves or its entire session closes.

Understand the moving parts

own_effect ties a keyed observer to a component. Direct effect calls return a disposer that the caller must own. Similarly, prefer owned timers/tasks and subscriptions over unmanaged background factories.

The bounded log below records run N and cleanup N. Incrementing should clean up the old run before recording the new run. Once the observer is removed, further increments must not append log entries until a new observer is attached.

Walk through the code

from collections.abc import Callable
from pysx import Fragment, own_effect, pysx, signal


def app() -> Fragment:
    count = signal(0)
    active = signal(True)
    log = signal("")
    entries: list[str] = []

    def record(text: str) -> None:
        entries.append(text)
        del entries[:-10]
        log.set(" | ".join(entries))

    def Observer() -> Fragment:
        def observe() -> Callable[[], None]:
            value = count()
            record(f"run {value}")

            return lambda: record(f"cleanup {value}")

        own_effect("lesson-observer", observe)

        return pysx(t"""
            p(id="observer-active"): "Observer attached"
        """)

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

    def toggle(_: object) -> None:
        active.set(not active())

    return pysx(t"""
        div:
            button(id="effect-increment" onClick={increment}): "Increment source"
            button(id="effect-toggle" onClick={toggle}): "Attach or dispose observer"
        output(id="effect-source"): {count}
        if {active}:
            Observer:
        output(id="effect-log" role="log"): {log}
    """)

own_effect owns the observer inside the conditional component. Its callback records run N and returns a cleanup that records cleanup N before rerun or disposal. While detached, changing the source cannot append a run; reattachment observes the current value. Only the last ten entries are retained.

Try it live

Increment, dispose the observer, increment again and reattach it. Use Reset demo to start a new log.

What to observe

Cleanup precedes rerun. A disposed observer produces no new entries.

0

Observer attached

run 0

Take this with you

Every effect, timer and task needs an owner and a definite end to its lifetime.