The Reactive MVU Pattern
Model-Update-Observable
In a standard MVU loop the View function runs on every Model change and produces a new virtual tree, which is then diffed against the previous one. MVUish.Avalonia keeps the Model and Update halves of Elm but replaces the diffing view with a direct binding:
- Model and Update stay pure and immutable.
Updateprocesses aMsgand returns the newModelplus a command. - View runs once at startup. It receives an
IObservable<Model>and adispatchfunction. - Bindings carry the updates. Each control property subscribes to the slice of the stream it needs, so only the properties that change are updated.
There is no tree diffing and no wrapper controls: the view returns real Avalonia controls, so third-party controls and layouts work without special support.
Programs
Program.mkProgram (F#) / Program.MkProgram (C#) takes init, update, and view. The builder functions add behavior:
F# |
C# |
Purpose |
|---|---|---|
|
|
Register the keyed subscription set; re-evaluated per update |
|
— |
Accumulate instead of replace subscriptions |
|
|
Exit message plus final-model handler |
|
|
Bind the update loop to one |
|
|
Trace message, model, and wanted sub ids |
|
|
Log messages, models, and active sub ids |
|
|
Handle command and update errors |
|
|
Start the loop and get the view |
|
|
View plus an |
|
|
Program tied to a control's visual-tree lifetime |
Update and dispatch are marshalled to the UI thread, and dispatch is thread-safe from any thread. Each program binds one dispatcher when it starts — Dispatcher.UIThread by default — and keeps it for its lifetime, so a replaced process global can no longer strand a running program; Program.withDispatcher (C# .WithDispatcher(...)) binds any IDispatcher explicitly — a headless harness binds its session's dispatcher, and a logic-only test binds an inline fake with no UI thread at all.
Commands
A Cmd<'Msg> (C# Action<Action<'Msg>, Action<string, exn>>) runs side effects and dispatches messages. Program routes errors from commands to the error handler with the message that caused them.
Common helpers:
F# |
C# |
Purpose |
|---|---|---|
|
|
No side effect |
|
|
Dispatch a message immediately |
|
— |
Effect that receives |
|
|
Plain |
|
|
Run several commands |
|
|
Remap a child command for composition |
|
|
Run a sync function, dispatch the result |
|
|
Run a sync function, dispatch the error |
|
|
Run a sync function, map success or error to messages |
|
— |
Run an |
|
— |
Same, with a custom async start |
|
|
Run a |
|
|
Run a |
|
|
Native ValueTask commands |
Threading
All async work a command starts runs on the rendering thread — the
program's bound dispatcher's thread, which is Dispatcher.UIThread unless
Program.withDispatcher bound another. Cmd.OfAsync starts with
Async.StartImmediate, and Cmd.OfTask / Cmd.OfValueTask await inside
a task that captures the UI SynchronizationContext, so every segment
between suspensions — including CPU-bound work — executes there, one
message at a time, and the resulting message comes back through the same
loop. I/O that truly suspends is the only part that overlaps.
Background processing must be explicit:
// hand the work to the pool and await it on the rendering thread
let! thing = Task.Run(fun () -> thing())
// F# task builder whose continuations stay on the pool
let! thing = backgroundTask { thing() }
// full control of the context round-trip
let thing = async {
let context = SynchronizationContext.Current
do! Async.SwitchToThreadPool()
let! result = doTheThing()
if not (isNull context) then
do! Async.SwitchToContext context
return result
}
Avalonia installs its own SynchronizationContext on the UI thread, so the
round-trip lands back on the rendering thread; note that
Async.StartImmediate and task awaits already restore the context on
their own — the manual pattern is for work that started on the pool, for
example under Cmd.OfAsyncWith Async.Start.
The loop reports once through OnError when a program that captured
Dispatcher.UIThread finds the global replaced (dispatcher drift — headless
isolation resets, a second session): posts from code still reading the
global then miss that program's dispatcher. Programs bound with
withDispatcher never report, because differing from the global is their
point.
Subscriptions
A Sub<'Msg> (C# CSub<Msg>, built with the Subscription helpers) is the set of external event sources the current model wants active. The program re-evaluates the set after every update and starts or stops subscriptions to match; see Subscriptions for the full guide.
F# |
C# |
Purpose |
|---|---|---|
|
|
No subscriptions |
|
|
Combine several subscription sets |
|
|
Scope child ids and translate child messages |
|
|
Dispatch a tick message on a timer |
|
|
Bridge a .NET event into messages |
|
|
Bridge any |
|
|
Bridge an Avalonia routed event |
|
|
End the set when a control detaches |
Lifecycle
Programs own resources: subscriptions, the update loop, and the model stream. runWithLifecycle returns the handle that releases all three; runWithLifetime ties that release to a control leaving the visual tree; withTermination makes a message do it. Completing the model stream ends every subscription derived from it and reverts bound properties to their defaults — details in Subscriptions.
Composition and scaling
Modules compose like standard Elmish modules. A parent model holds the child models, and the parent maps child commands, subscriptions, and dispatchers:
Command.Map/Cmd.maproutes child commands upward.Subscription.Map/Sub.maproutes child subscriptions upward, scoping their ids with a prefix.Subscription.Batch/Sub.batchcombines subscription sets.
In the view, slice the parent stream with Observable.map / Select and hand each child its own observable and dispatch function:
let view (model: IObservable<Model>) (dispatch: Dispatch<Msg>) =
let clockObs = model |> Observable.map(fun m -> m.Clock)
let dispatchClock = ClockMsg >> dispatch
StackPanel().Children(
Clock.view clockObs dispatchClock
)
The dashboard sample wires three child modules this way, in both languages.
type Async = static member AsBeginEnd: computation: ('Arg -> Async<'T>) -> ('Arg * AsyncCallback * objnull -> IAsyncResult) * (IAsyncResult -> 'T) * (IAsyncResult -> unit) static member AwaitEvent: event: IEvent<'Del,'T> * ?cancelAction: (unit -> unit) -> Async<'T> (requires delegate and 'Del :> Delegate and 'Del: not null) static member AwaitIAsyncResult: iar: IAsyncResult * ?millisecondsTimeout: int -> Async<bool> static member AwaitTask: task: Task<'T> -> Async<'T> + 1 overload static member AwaitWaitHandle: waitHandle: WaitHandle * ?millisecondsTimeout: int -> Async<bool> static member CancelDefaultToken: unit -> unit static member Catch: computation: Async<'T> -> Async<Choice<'T,exn>> static member Choice: computations: Async<'T option> seq -> Async<'T option> static member FromBeginEnd: beginAction: (AsyncCallback * objnull -> IAsyncResult) * endAction: (IAsyncResult -> 'T) * ?cancelAction: (unit -> unit) -> Async<'T> + 3 overloads static member FromContinuations: callback: (('T -> unit) * (exn -> unit) * (OperationCanceledException -> unit) -> unit) -> Async<'T> ...
--------------------
type Async<'T>
MVUish.Avalonia