Not at all surprisingly, it turns out that F# events need not be the crufty structures I showed in my previous post.
First, Xamarin's David Siegel suggested "Let the Event type be inferred, don't define a delegate type, and send simple typed values rather than EventArgs:"
open System
type Control() =
let hello = Event\<_>()
member this.Hello = hello.Publish
member this.Speak() = hello.Trigger "yo!"
let control = Control()
control.Hello.Add \< | fun msg ->
printfn "Received '%s'" msg
control.Speak()
While Ryan Riley suggested a step further down the reactive line:
To remain consistent with your pipe forwards when using events, you can use the Observable module:
do myItem.FooEvent |> Observable.add (fun o args -> …)
or even
let disposable = myItem.FooEvent |> Observable.subscribe (fun o args -> …)
You can also expose an event as an IObservable rather than as an event if you like:
FooEvent.Publish :> IObservable
I also learned from \@kemnet that List.choose id
is the idiomatic way to transform a List<option>
into a List
of Some
values.