State Management & Events
This content is for v1.2.0. Switch to the latest version for up-to-date documentation.
In ZKite, the user interface is a pure function of application state. When state changes, the framework re-evaluates the view and updates native views.
Declaring State with @store
Section titled “Declaring State with @store”Application state is declared using the @store decorator. Annotated fields define the state values with default fallbacks:
from zkite import store
@storeclass ProfileStore: username: str = "Alice" email: str = "" is_notifications_enabled: bool = True tap_count: int = 0
profile = ProfileStore()Annotated store parameters in a view are automatically supplied by the framework when requested.
Mutating State with store.update()
Section titled “Mutating State with store.update()”To change values and request an updated interface, always call the store’s update method:
# Update one or multiple fieldsprofile.update( tap_count=profile.tap_count + 1, is_notifications_enabled=False)Controlled Values
Section titled “Controlled Values”Interactive widgets (TextField, Switch, Checkbox, Radio, Slider, Select) are controlled widgets:
- The displayed value comes from a store field.
- User actions invoke event callbacks that call
store.update(). - If a callback does not update the store, a subsequent render restores the previous value.
from zkite import TextField
TextField( "p-3 bg-slate-900 rounded-lg text-white", value=profile.username, on_change=lambda text: profile.update(username=text), placeholder="Enter username...",)Background I/O with the Task API (New in 1.1.2)
Section titled “Background I/O with the Task API (New in 1.1.2)”view() and ordinary event callbacks run synchronously on the UI thread. Any blocking operation—such as urllib.request, an HTTP client call, or reading a large local file—freezes user input and skips frames until it finishes.
ZKite 1.1.2 introduces the Task API for nonblocking background I/O. Create tasks at module scope, launch them from event handlers, and read their reactive states (loading, data, error) directly inside view():
import jsonfrom urllib.request import urlopenfrom zkite import Button, Column, Task, Text
# 1. Define task at module scoperequest = Task()
def fetch_items(): with urlopen("https://api.example.com/items", timeout=15) as response: return json.loads(response.read())
def view(): return Column( "flex-1 p-6 gap-4 bg-white", Button( "bg-orange-600 text-white p-4 rounded-xl", "Refresh Data", on_tap=lambda: request.start(fetch_items), disabled=request.loading, ), # Read reactive task state directly Text("text-slate-700", "Loading…" if request.loading else str(request.data)), Text("text-red-700", str(request.error) if request.error else ""), )Task Lifecycle & Mechanics
Section titled “Task Lifecycle & Mechanics”- Nonblocking Dispatch:
Task.start(fn, *args, **kwargs)returns immediately. Work executes across 4 managed background workers with a bounded admission queue of 32 jobs. - Reactive Frame Push: When the worker returns a value, the framework automatically updates
request.loading,request.data, andrequest.errorunder the render lock and pushes a fresh UI frame. - Data Retention: During re-fetches or failures, the previous successful
dataremains available so the UI doesn’t abruptly collapse to blank. - Automatic Invalidation & Cancellation: Starting the same task again invalidates earlier in-flight results. Calling
request.cancel()or triggering a hot reload immediately discards stale results. - Return Values vs. Direct Mutation: Workers must return data rather than directly updating widgets or stores from thread code.
- Async Event Callbacks: Async event callbacks are also supported, but synchronous work inside them still blocks their event loop; use
Taskfor blocking network or file I/O.
Asynchronous Handlers & Device Operations (New in 1.2.0)
Section titled “Asynchronous Handlers & Device Operations (New in 1.2.0)”While Task is optimized for synchronous worker functions (like urllib), ZKite 1.2.0 introduces first-class support for async def event handlers on the background async event loop. This enables nonblocking mobile device operations such as file pickers, camera capture, sensor watches, and audio recordings:
from zkite import Button, Column, Text, storefrom zkite import filesfrom zkite.errors import DeviceError
@storeclass FileState: filename: str = "None" busy: bool = False
state = FileState()
def view(): async def pick_doc(): state.update(busy=True) try: doc = await files.pick(types=["application/pdf"]) if doc is not None: state.update(filename=doc.name) except DeviceError as err: state.update(filename=f"Error: {err}") finally: state.update(busy=False)
return Column("p-6 gap-4", Button("p-4 bg-blue-600 text-white rounded-xl", "Choose PDF", on_tap=pick_doc, disabled=state.busy), Text("text-slate-800", f"Selected: {state.filename}") )- Thread-Safe Atomic Commits:
state.update(...)called from within an async coroutine is atomic with respect to native frame rendering. - Hot Reload Protection: Hot reloads automatically cancel active async device coroutines and prevent cancelled coroutines from modifying store state.
- Typed Exceptions: Catch typed
DeviceErrorexceptions (PermissionDenied,ResourceBusy,UnsupportedFeature, etc.) to guide the user gracefully. See Async Handlers & Error Model for details.
Error Handling & Public Diagnostics
Section titled “Error Handling & Public Diagnostics”1. Cleaner Public Errors (New in 1.1.2)
Section titled “1. Cleaner Public Errors (New in 1.1.2)”Framework errors no longer expose internal planning-document references or internal module paths. They provide clear, actionable guidance pointing directly to application entry points (such as main.py’s view() function or misconfigured widget properties).
2. Standalone vs. Development Error Behavior
Section titled “2. Standalone vs. Development Error Behavior”- Standalone APK / AAB: Uncaught Python startup, render, and event exceptions display a clean generic restart message rather than rendering raw traceback text on user screens.
- Diagnostics: Full tracebacks are preserved in device logcat (
zkite run --logs). - Development Mode (
zkite dev): Retains interactive error overlays with detailed code frames. Invalid dependency changes are reported in the dev console without crashing the running app on device.
