Yesterday I showed how we can map some of the Rx operators to an API which looks more like the F# base classes. Today I wanted to use these mapped operators in a WPF-application written in F#.
F# gives us a nice way to use events as first class citizen (via IEvent) but these events implement their own version of IObservable<T> (in FSharp.Core.dll), which is unfortunately incompatible with the Rx version and therefore with the mapped API.
The solution I found is to wrap the F# IEvent with a Rx IObservable<T>:
/// Generates an observable from an IEvent
let fromEvent (event:IEvent<_,_>) =
Observable.Create<_>(fun x ->
event.Subscribe x.OnNext |> ignore
new System.Action(fun () -> ()))
Now we are able to use the WPF events as observables:
// Register ListBox Commands
listBox1.KeyDown
|> Observable.fromEvent
|> Observable.filter (fun args -> args.Key = Key.Delete)
|> Observable.subscribe deleteElement
I am interested if someone has a different and maybe better solution to this problem.
Updated: 21.12.2009 – Observable.Context is no longer supported by Rx ==> Removed
Tags: F#, Reactive Framework