In FuncUI with Elmish, you don't directly use observables like in ReactiveUI. Instead, FuncUI follows the Elmish architecture pattern where UI events are handled through messages and the update function.
Here's how you can handle mouse move events in FuncUI:
type Msg =
| MouseMoved of Point
let update (msg: Msg) (model: Model) =
match msg with
| MouseMoved point ->
// Handle the mouse position
{ model with MousePosition = point }, Cmd.none
let view (model: Model) (dispatch: Msg -> unit) =
Canvas.create [
Canvas.background Brushes.LightGray
Canvas.onPointerMoved (fun args ->
let point = args.GetPosition(args.Source :?> IVisual)
dispatch (MouseMoved point)
)
// Your canvas content here
]
If you really need observable-like behavior for scenarios like throttling or complex event processing, you can create a subscription that bridges observables to Elmish messages:
open System
open Avalonia.Input
open Avalonia.Interactivity
let mouseMoveSub (canvas: Canvas) : IObservable<Point> =
canvas.GetObservable(InputElement.PointerMovedEvent)
|> Observable.map (fun args ->
let args = args :?> PointerEventArgs
args.GetPosition(canvas))
// In your Elmish program
let subscription model =
let sub dispatch =
// You'd need to get a reference to your canvas somehow
// This is just a conceptual example
let mouseSub =
mouseMoveSub canvasRef
|> Observable.throttle (TimeSpan.FromMilliseconds 50.0)
|> Observable.subscribe (fun point ->
dispatch (MouseMoved point))
{ new IDisposable with
member _.Dispose() = mouseSub.Dispose() }
Cmd.ofSub sub
However, the idiomatic FuncUI/Elmish way is to handle events directly in the view function using the onPointerMoved, onPointerPressed, etc. attributes rather than working with observables. This keeps your code simpler and more aligned with the Elmish architecture.