How to convert a WPF Button.Click Event into Observable using Rx and F#
The easiest way I know of to make an IObservable<_>
out of a WPF Button.Click event is to cast it:
open Systemopen System.Windows.Controlslet btn = new Button()let obsClick = btn.Click :> IObservable<_>
Examining obsClick...
val obsClick : IObservable<Windows.RoutedEventArgs>
This is possible because the F# representation of standard .NET events is the type (in this case) IEvent<Windows.RoutedEventHandler,Windows.RoutedEventArgs>
. As you can see from the documentation, IEvent implements IObservable. In other words, in F# every single event already is an IObservable
.
Joel Mueller is spot on, so just for the record: a direct translation of the C# code would be
Observable.FromEvent( (fun h -> RoutedEventHandler(fun sender e -> h.Invoke(sender, e))), (fun h -> b.Click.AddHandler h), (fun h -> b.Click.RemoveHandler h))