Async resources and server updates
Understand the moving parts
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."
""")Try it live
What to observe
Server setup:
Browser mount: