3.3. Getting Started with VMx — Python¶
This tutorial walks you through building viewmodels with the VMx Python library.
You will build a ComponentVMOf[UserModel], a RelayCommand with a reactive
trigger, and a tab composite with tab selection — all in a Python REPL,
script, or test. The code blocks form one program in page order. Option A and Option B
of section 3.3.2 are alternatives, and the later blocks use the hub and dispatcher of
Option A.
For the contracts behind each type, see the component family, command families, and composite family.
3.3.1. Install¶
Add VMx as described in Installation. PyPI provides
vmx 3.23.0. Examples that need a later source line state their minimum
version; the Python section of the installation page installs the source line
from a checkout.
To start a new console project, use the Python console starter template in
starters/python-console/. It was verified againstvmx3.23.0 from PyPI. From a VMx checkout, runpython3 tools/create-starter.py --channel python-console. The command writes the project to a new directory outside the checkout. It creates a virtual environment there, installs the exact PyPI version and runs the starter's smoke test.
3.3.2. Wire Up MessageHub And RxDispatcher¶
The viewmodels in this tutorial need two services: a hub that carries messages between viewmodels and a dispatcher that knows about your event loop or UI thread.
3.3.2.1. Option A — Immediate (Console / Synchronous Tests)¶
from vmx.messages import Message
from vmx.services import MessageHub, RxDispatcher
hub: MessageHub[Message] = MessageHub()
dispatcher = RxDispatcher.immediate()
# Both foreground and background schedulers are ImmediateScheduler — safe for
# console scripts and pytest suites where there is no event loop.
3.3.2.2. Option B — asyncio-Based UI (Textual, etc.)¶
import asyncio
from vmx.messages import Message
from vmx.services import MessageHub, RxDispatcher
async def main() -> None:
loop = asyncio.get_running_loop()
hub: MessageHub[Message] = MessageHub()
dispatcher = RxDispatcher.asyncio(loop)
# Source 3.23.2 or later maps foreground to AsyncIOThreadSafeScheduler(loop).
# Background stays on ThreadPoolScheduler.
...
asyncio.run(main())
asyncio.get_running_loop() is preferred over asyncio.get_event_loop(),
which has been a DeprecationWarning since Python 3.10 when no loop is
running.
You can also inject the two schedulers directly if you need a custom pairing:
import asyncio
from reactivex.scheduler import ThreadPoolScheduler
from reactivex.scheduler.eventloop import AsyncIOThreadSafeScheduler
from vmx.services import RxDispatcher
async def main() -> None:
loop = asyncio.get_running_loop()
# This pairing gives vmx 3.23.0 from PyPI the thread-safe scheduler (tested with RxPY 4.0.4).
dispatcher = RxDispatcher(
foreground=AsyncIOThreadSafeScheduler(loop),
background=ThreadPoolScheduler(),
)
3.3.3. Build A ComponentVMOf[UserModel]¶
ComponentVMOf[M] is the primary leaf viewmodel. It holds a typed model,
fires PropertyChangedMessage on the hub when the model changes, and
participates in the lifecycle state machine
(DESTRUCTED → CONSTRUCTING → CONSTRUCTED → DESTRUCTING → DESTRUCTED).
from dataclasses import dataclass
from vmx.components import ComponentVMOf
from vmx.messages import Message, PropertyChangedMessage
from vmx.services import MessageHub, RxDispatcher
# A simple domain model — use your own real types here.
@dataclass(frozen=True)
class UserModel:
name: str
email: str
# Build the viewmodel — every builder setter returns a NEW builder (immutable).
user_vm: ComponentVMOf[UserModel] = (
ComponentVMOf[UserModel].builder()
.name("user-card")
.model(UserModel("Alice", "alice@example.com"))
.services(hub, dispatcher)
# Derive a display hint from the model.
.modeled_hinter(lambda m: m.name)
# Optional: callback when model is set to a new value.
.on_model_changed(lambda m: print(f"Model updated → {m.name}"))
.on_construct(lambda: print("user-card constructed"))
.on_destruct(lambda: print("user-card destructed"))
.build()
)
# Subscribe to hub messages BEFORE constructing so you don't miss any.
# reactivex.operators has no OfType; filter by isinstance directly in the
# subscriber.
def on_message(msg: Message) -> None:
if isinstance(msg, PropertyChangedMessage) and msg.sender is user_vm:
print(f"Property '{msg.property_name}' changed on {msg.sender_name}")
hub.messages.subscribe(on_message)
# Alternatively, subscribe via the VM's own property_changed observable,
# which emits property name strings (snake_case).
user_vm.property_changed.subscribe(
lambda prop: print(f" [property_changed] {prop}")
)
# construct() transitions DESTRUCTED → CONSTRUCTING → CONSTRUCTED.
# This fires the VM's on_construct callback. Model assignment is already valid
# before construction and remains valid until the terminal DISPOSED state.
user_vm.construct()
# stdout: " [property_changed] status"
# stdout: " [property_changed] is_constructed"
# stdout: "user-card constructed"
# stdout: " [property_changed] status"
# stdout: " [property_changed] is_constructed"
# Update the model — triggers on_model_changed and publishes
# PropertyChangedMessage for "model" (and "modeled_hint" if it changed).
user_vm.model = UserModel("Alice Smith", "asmith@example.com")
# stdout: "Property 'model' changed on user-card"
# stdout: " [property_changed] model"
# stdout: "Property 'modeled_hint' changed on user-card"
# stdout: " [property_changed] modeled_hint"
# stdout: "Model updated → Alice Smith"
print(user_vm.modeled_hint) # "Alice Smith" (modeled_hinter result)
print(user_vm.status.name) # CONSTRUCTED
See the component family for the full
ComponentVMOfProto[M]contract and Services, Messages & Dispatching for thePropertyChangedMessageschema.
3.3.4. Build A RelayCommand¶
RelayCommand wraps an optional callable task, an optional predicate that
gates execution, and a set of Observable triggers that signal can_execute
may have changed.
from reactivex.subject import Subject
from vmx.commands import RelayCommand
# A Subject you fire whenever the predicate outcome may have changed.
can_save_trigger: Subject[object] = Subject()
is_dirty = False
def save_task() -> None:
global is_dirty
print("Saving…")
is_dirty = False
can_save_trigger.on_next(None) # re-evaluate can_execute
save_command = (
RelayCommand.builder()
.task(save_task)
.predicate(lambda: is_dirty)
.triggers(can_save_trigger)
.build()
)
# can_execute is False until is_dirty is True.
print(save_command.can_execute()) # False
is_dirty = True
can_save_trigger.on_next(None) # fires can_execute_changed
# Subscribe to re-evaluation notifications.
save_command.can_execute_changed.subscribe(
lambda _: print(f" can_execute is now {save_command.can_execute()}")
)
print(save_command.can_execute()) # True
save_command.execute()
# stdout: "Saving…"
# stdout: " can_execute is now False" (the task fires the trigger)
print(save_command.can_execute()) # False again
# Dispose to unsubscribe all trigger subscriptions. Disposal sends one final
# can_execute_changed notification before it completes the stream.
save_command.dispose()
# stdout: " can_execute is now False"
See command families for the full command contract, including the "predicate-false gates execute" rule (CMD-007).
3.3.5. Build A Tab Composite¶
CompositeVM[VM] owns an ordered child collection and a current selection.
Children are provided by a factory callable that runs lazily on the first
construct() call.
from dataclasses import dataclass
from vmx.components import ComponentVMOf
from vmx.composites import CompositeVM
from vmx.messages import PropertyChangedMessage, when_property_changed
from vmx.services import MessageHub, RxDispatcher
@dataclass(frozen=True)
class TabModel:
title: str
# Build two tab children — they share the same hub and dispatcher.
tab1: ComponentVMOf[TabModel] = (
ComponentVMOf[TabModel].builder()
.name("home-tab")
.model(TabModel("Home"))
.services(hub, dispatcher)
.build()
)
tab2: ComponentVMOf[TabModel] = (
ComponentVMOf[TabModel].builder()
.name("settings-tab")
.model(TabModel("Settings"))
.services(hub, dispatcher)
.build()
)
# Build the composite. The children factory is evaluated on construct().
tabs: CompositeVM[ComponentVMOf[TabModel]] = (
CompositeVM[ComponentVMOf[TabModel]].builder()
.name("tab-bar")
.services(hub, dispatcher)
.children(lambda: [tab1, tab2])
.on_construct(lambda: print("tab-bar constructing"))
.build()
)
# Watch for current-selection changes via the hub.
def on_current(_: PropertyChangedMessage[object]) -> None:
title = tabs.current.model.title if tabs.current else "(none)"
print(f"Selected tab: {title}")
when_property_changed(hub, tabs, "current").subscribe(on_current)
# The hook runs while the composite is Constructing. Each child then
# constructs, and the composite becomes Constructed after the last child.
tabs.construct()
# stdout: "tab-bar constructing"
# Select a tab — publishes PropertyChangedMessage for "current" and
# sets child.is_current.
tabs.current = tab2 # stdout: "Selected tab: Settings"
tabs.current = tab1 # stdout: "Selected tab: Home"
print([child.name for child in tabs]) # ['home-tab', 'settings-tab']
print(tab2.is_current) # False
See the composite family for the full
CompositeVMProto[VM]contract, including theMutableSequencesemantics andCollectionChangedEvent.
3.3.6. Lifecycle And Cleanup¶
The VMs in this tutorial have five lifecycle states. Four of them form a
reversible cycle, DESTRUCTED → CONSTRUCTING → CONSTRUCTED → DESTRUCTING → DESTRUCTED. The fifth state, DISPOSED, is terminal.
from vmx.lifecycle.status import ConstructionStatus
print(user_vm.status.name) # CONSTRUCTED (after construct())
# reconstruct() is destruct() + construct() in a single call. It is only valid
# from CONSTRUCTED (can_reconstruct() is True iff status == CONSTRUCTED); it
# round-trips through DESTRUCTED and back to CONSTRUCTED.
user_vm.reconstruct()
print(user_vm.status.name) # CONSTRUCTED
# destruct() transitions back to DESTRUCTED and runs on_destruct.
user_vm.destruct()
print(user_vm.status.name) # DESTRUCTED
# dispose() is terminal and idempotent. Calling construct() or destruct() on a
# disposed VM raises StatusTransitionError.
user_vm.dispose()
print(user_vm.status.name) # DISPOSED
# CompositeVM.dispose() disposes children, then itself.
tabs.dispose()
Dispose the hub last, after every viewmodel that uses it. MessageHub.dispose()
completes the underlying Rx subject. The threading examples below still use the
hub, so the full shutdown sequence appears after them.
See Lifecycle & Messaging for the transition table, the error of a refused operation, and the callback ordering.
3.3.7. Threading¶
RxDispatcher pairs two Rx schedulers:
| Scheduler | Typical mapping |
|---|---|
dispatcher.foreground |
UI thread / asyncio event loop |
dispatcher.background |
Thread-pool (blocking I/O, CPU-bound work) |
All hub observations delivered on foreground are safe to bind to UI controls.
Use observe_on from reactivex.operators to marshal:
import reactivex.operators as ops
hub.messages.pipe(
ops.filter(lambda msg: isinstance(msg, PropertyChangedMessage)),
ops.observe_on(dispatcher.foreground), # marshal to UI scheduler
).subscribe(lambda msg: update_label(msg)) # safe to touch UI here
The next example loads data in the background before construct(). It builds
a new viewmodel because section 3.3.6 disposed user_vm.
import reactivex as rx
import reactivex.operators as ops
profile_vm: ComponentVMOf[UserModel] = (
ComponentVMOf[UserModel].builder()
.name("profile")
.model(UserModel("", ""))
.services(hub, dispatcher)
.build()
)
def apply_remote_data(data: UserModel) -> None:
profile_vm.model = data
profile_vm.construct()
rx.from_callable(lambda: load_from_database(), scheduler=dispatcher.background).pipe(
ops.observe_on(dispatcher.foreground),
).subscribe(apply_remote_data)
At shutdown, dispose the viewmodels first and the hub last:
profile_vm.dispose()
hub.dispose()
When using RxDispatcher.asyncio(loop), the foreground scheduler is
AsyncIOThreadSafeScheduler(loop), which safely posts worker completions back
to the given event loop. The host still owns the loop and the independent
background pool; see Python asyncio dispatcher ownership
for teardown guidance.
3.3.7.1. Start And Cancel An Async Resource From Synchronous Code¶
The no-loop start and cancel behavior, its source-version floor, and a complete program are in Services, Messages & Dispatching.
See Services, Messages & Dispatching for the foreground rules for property and collection changes.
3.3.8. Where To Go Next¶
| Resource | Documentation page |
|---|---|
| Specification status | Specification & Conformance |
| Lifecycle contract | Lifecycle & Messaging |
| Messages & threading | Services, Messages & Dispatching |
| Commands | Command Families |
| Component contract | Component Family |
| Composite contract | Composite Family |
| Builders & tree | Builders, Collections & Tree Utilities |
| Architecture | Architecture Map |
| Python status | Python Flavor |
| Examples | Smaller Examples |