pysxLearn by building

Runtime and resilience · Lesson 17 of 28

Async resources and server updates

Start, replace and cancel owned asynchronous work without stale publication.

An interface must remain usable while work is pending. A resource makes that lifetime visible through pending, success, error and cancelled states. The loader runs independently, while its eventual publication belongs to the owning session.

Await slow work outside a synchronous mutation turn. When background work needs to change signals, await push with a synchronous callback. Keeping that boundary explicit avoids holding a batch or a session mutation across arbitrary I/O.

Understand the moving parts

Reload replaces unfinished work and suppresses results from superseded generations. Cancellation is therefore more than showing a cancelled label: the old operation must lose the ability to publish over the current state.

The local loader below deliberately waits long enough to interact with. Type a draft while it runs, trigger a replacement, and cancel another request. Your draft should remain editable and a cancelled result must not appear later.

Walk through the code

import asyncio
from pysx import Fragment, derived, on_mount, on_setup, push, pysx, resource, signal


def app(*, server_rendering: bool = False) -> Fragment:
    draft = signal("")
    setups = signal(0)
    mounts = signal(0)
    generation = 0
    failing = signal(False)
    on_setup(lambda: setups.update(lambda value: value + 1))
    on_mount(lambda: mounts.update(lambda value: value + 1))

    async def load() -> str:
        nonlocal generation
        generation += 1
        current = generation
        should_fail = await push(failing)
        await asyncio.sleep(0.4)

        if should_fail:
            raise ValueError("intentional lesson resource failure")

        return f"Result {current}"

    result = resource("lesson-resource", load)
    status = derived(lambda: result().status)
    message = derived(lambda: result().value or "No completed result")

    def reload(_: object) -> None:
        failing.set(False)
        result.reload()

    def cancel(_: object) -> None:
        result.cancel()

    def fail(_: object) -> None:
        failing.set(True)
        result.reload()

    return pysx(t"""
        label(for="resource-draft"): "Draft stays editable during work"
        input(id="resource-draft" bindValue={draft})
        div:
            button(id="resource-reload" onClick={reload}): "Reload / retry"
            button(id="resource-cancel" onClick={cancel}): "Cancel"
            button(id="resource-fail" onClick={fail}): "Fail next request"
        output(id="resource-status" role="status"): {status}
        output(id="resource-message"): {message}
        p: "Server setup: "
        output(id="resource-setups"): {setups}
        p: "Browser mount: "
        output(id="resource-mounts"): {mounts}
        if {server_rendering}:
            p: "This content was included in the first HTTP response."
    """)

The loader waits 0.4 seconds and returns a numbered result. Reload replaces work, Cancel revokes the pending request, and Fail next request exercises the error path. The independent draft remains editable. The status and result readouts derive from the resource state.

Try it live

Reload twice before completion. Cancel a third request and wait past its original deadline.

What to observe

Only the latest live request publishes. Cancelled work stays cancelled and your draft remains.

pendingNo completed result

Server setup:

1

Browser mount:

0

Take this with you

Own asynchronous work, serialize mutations and guard publication by generation.