3.6. Getting Started with VMx — Rust¶
This tutorial walks you through building viewmodels with the VMx Rust crate.
You will build a ComponentVm<Model>, a RelayCommand, and a CompositeVm<T>
with child selection — all in a plain Cargo binary.
The Rust source line v0.37.0 declares
MIN_SPEC_VERSION = "3.30.0"and has behavioral tests for every library conformance ID. The Rust flavor page describes its status and parity evidence.For the contracts behind each type, see the component family, command families, and composite family.
3.6.1. Install¶
Add VMx as described in Installation. The vmx-rs crate
is not published to crates.io, so the Rust section of that page adds it as a
path or git dependency. Code imports the crate as vmx.
The crate declares only serde and thiserror as runtime dependencies. Its
reactive primitives are VMx-owned hot-stream facades, so it pulls in no
third-party reactive runtime.
3.6.2. Wire Up MessageHub And A Dispatcher¶
The viewmodels in this tutorial need two services: a hub that carries messages
between viewmodels and a dispatcher that routes scheduled work. NullDispatcher
runs foreground and background work inline on the calling thread — the right
choice for tests and synchronous programs. It is Copy, so it can be handed to
several viewmodels without cloning.
DefaultDispatcher owns dedicated serial foreground and background workers.
ManualDispatcher provides separate foreground and background queues for
deterministic tests. NullDispatcher and ImmediateDispatcher deliberately run
both channels inline.
A hub keeps no message after delivering it. When a test or diagnostic needs to
inspect traffic, attach a bounded MessageRecorder with hub.record(capacity)
before the sends. It keeps the newest capacity messages and counts the ones it
evicts (ADR-0141).
use vmx::{Message, MessageHub, NullDispatcher};
fn main() {
let hub = MessageHub::new();
let dispatcher = NullDispatcher::new();
let recorder = hub.record(64);
hub.send(Message::Custom {
sender_id: 1,
sender_name: "app".into(),
name: "ready".into(),
});
assert_eq!(recorder.len(), 1);
let _ = dispatcher;
}
Enable background lifecycle work with
ComponentVm::builder().background(true) (or the read-only component builder).
Terminal state and publication are committed on foreground. Subscribe to the
hot background_errors() stream for hook failures after the fire-and-forget
call returns; the stream completes on disposal.
Subscribe to the hub to observe its messages. The handler runs for every message, so match only the variants you need:
use vmx::{Message, MessageHub};
fn main() {
let hub = MessageHub::new();
let _subscription = hub.subscribe(|message| {
if let Message::PropertyChanged(change) = message {
println!("property changed: {}", change.property_name);
}
});
}
3.6.3. Build A ComponentVm<Model>¶
ComponentVm<M> is the primary leaf viewmodel. It holds a typed model, publishes
a property message on the hub when the model changes, and participates in the
lifecycle state machine. with_model constructs one directly; the model type
must be Clone + PartialEq + Send + 'static.
use vmx::{ComponentVm, MessageHub, NullDispatcher, VmxResult};
#[derive(Clone, PartialEq)]
struct UserModel {
name: String,
email: String,
}
fn main() -> VmxResult<()> {
let hub = MessageHub::new();
let dispatcher = NullDispatcher::new();
let user = ComponentVm::with_model(
"user-card",
UserModel { name: "Alice".into(), email: "alice@example.com".into() },
hub.clone(),
dispatcher,
)
.with_model_hint(|model| model.name.clone());
user.construct()?;
assert!(user.is_constructed());
user.set_model(UserModel { name: "Alice Smith".into(), email: "asmith@example.com".into() });
assert_eq!(user.model().name, "Alice Smith");
assert_eq!(user.modeled_hint(), "Alice Smith");
user.dispose()
}
See the component family for the full contract.
3.6.4. Build A RelayCommand¶
RelayCommand wraps an action closure, an optional can_execute predicate, and
zero or more trigger hubs that announce when eligibility may have changed. Use
RelayCommand::new for the action-only form, or the builder to add a predicate.
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use vmx::{Command, RelayCommand};
fn main() {
let is_dirty = Arc::new(AtomicBool::new(false));
let dirty_for_predicate = is_dirty.clone();
let save = RelayCommand::builder()
.action(|| println!("Saving..."))
.can_execute(move || dirty_for_predicate.load(Ordering::Acquire))
.build();
assert!(!save.can_execute());
is_dirty.store(true, Ordering::Release);
assert!(save.can_execute());
save.execute(); // prints "Saving..."
save.dispose();
}
See command families for the full contract.
Commandis the object-safe trait exposingcan_execute()andexecute().
AsyncRelayCommand runs its task on a worker thread. A fire-and-forget
execute() publishes each failure on error_stream() as the original
VmxError; an awaited execute_async() returns it instead.
use std::sync::mpsc;
use vmx::{AsyncRelayCommand, VmxError};
fn main() {
let save = AsyncRelayCommand::new(|_cancellation| {
Err(VmxError::InvalidArgument("server rejected the change".into()))
});
let (failed, failures) = mpsc::channel();
let _failures = save.error_stream().subscribe(move |error| {
failed.send(error).unwrap();
});
save.execute();
let error = failures.recv().unwrap();
assert_eq!(
error,
VmxError::InvalidArgument("server rejected the change".into())
);
save.dispose();
}
Pass a trigger hub to the builder to re-evaluate can_execute when that hub
announces a change:
use vmx::{Command, MessageHub, RelayCommand};
fn main() {
let hub = MessageHub::new();
let save = RelayCommand::builder()
.action(|| println!("Saving..."))
.trigger(hub.clone())
.build();
assert!(save.can_execute());
}
3.6.5. Build A CompositeVm<T> With Selection¶
CompositeVm<T> owns an ordered child collection and a current selection slot.
Children come from a factory evaluated on the first construct(); an optional
current selector seeds the initial selection.
use vmx::{
ComponentVm, CompositeVm, FilteredCompositeVm, MessageHub, NullDispatcher, VmxResult,
};
fn build_tabs() -> VmxResult<()> {
let hub = MessageHub::new();
let dispatcher = NullDispatcher::new();
let home = ComponentVm::with_model("home-tab", "Home", hub.clone(), dispatcher);
let settings = ComponentVm::with_model("settings-tab", "Settings", hub.clone(), dispatcher);
let tabs = CompositeVm::builder()
.name("tab-bar")
.services(hub, dispatcher)
.children({
let children = vec![home.clone(), settings.clone()];
move || children.clone()
})
.current(|items| items.first().cloned())
.build()?;
tabs.construct()?;
assert_eq!(tabs.len(), 2);
assert_eq!(tabs.current().map(|c| c.name()), Some("home-tab".to_string()));
tabs.select_component(&settings)?;
assert_eq!(tabs.current().map(|c| c.name()), Some("settings-tab".to_string()));
let matches = FilteredCompositeVm::new(tabs.clone(), |tab| tab.model().contains("Home"));
assert_eq!(matches.visible_count(), 1);
tabs.dispose()
}
fn main() -> VmxResult<()> {
build_tabs()
}
The example also projects a live filtered view with FilteredCompositeVm. See
the composite family for
the full contract.
3.6.6. Lifecycle And Cleanup¶
The viewmodels 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. The mutating transitions
return VmxResult<()>. An illegal transition, such as constructing a disposed
viewmodel, returns an Err and does not panic.
use vmx::{ComponentVm, ConstructionStatus, VmxResult};
fn main() -> VmxResult<()> {
let user = ComponentVm::new("user");
user.construct()?;
assert_eq!(user.status(), ConstructionStatus::Constructed);
user.reconstruct()?; // destruct + construct in one call; round-trips to Constructed
assert_eq!(user.status(), ConstructionStatus::Constructed);
user.destruct()?;
assert_eq!(user.status(), ConstructionStatus::Destructed);
user.dispose()?; // idempotent and terminal
assert_eq!(user.status(), ConstructionStatus::Disposed);
Ok(())
}
Selecting a non-child returns Err(VmxError::NonChild) rather than trapping, so
callers can branch on the result. Builders return Err from build() when a
required field is missing.
See Lifecycle & Messaging for the transition table, the error of a refused operation, and the callback ordering.
3.6.7. 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 |
| Rust status | Rust Flavor |
| Rust examples | Rust TUI Notes Showcase |