August Feng

fsharp events

About

Just some explorations on interoperability with dotnet events.

Explorations

Basic demonstration

The .Publish property returns an IEvent and we can use it to add handlers.

The .Trigger method allows to trigger events with parameters.

  let e = new Event<string>()

  [<EntryPoint>]
  let main _ =
      e.Publish.Add(fun s -> s.ToUpper() |> printf "%s")
      e.Trigger("helloworld")
      0

Modules, types and interfaces

The IEvent<T> type provides the .Add method to events, which is just a wrapper around the IObservable<T>'s Subscribe method: it builds an IObserver<T> using the provided lambda.

The Event module contains functions that can is more functional friendly:

  Event.add (fun s -> printfn "%s!" s) e.Publish

The Event<T> is a class that implements Publish and Trigger methods.

References

I visited the FSharp.Core's Event and Observables documentation for most of these information.