2

How do I register and implement event handlers for .Net events within F#?

I reviewed this link but it seems a bit verbose.

Example:

namespace Core

open Lego.Ev3.Core
open Lego.Ev3.Desktop

type LegoExample() = 
    let _brick = Brick(BluetoothCommunication("COM3"))
    _brick.Changed += OnBrickChanged

    let OnBrickChanged = 
        // some logic goes here...
Scott Nimrod
  • 11,206
  • 11
  • 54
  • 118

1 Answers1

5

In F#, events are represented as IEvent<T> values which inherit from IObservable<T> and so they are just ordinary values - not a special language construct.

You can register a handler using the Add method:

type LegoExample() = 
    let brick = Brick(BluetoothCommunication("COM3"))
    do brick.Changed.Add(fun e ->
        // some logic goes here...
    )

You need the do keyword here if you want to register the handler inside the constructor of LegoExample.

Alternatively, you can also use various functions from the Observable module - those implement basic functionality similar to the one provided by Rx:

type LegoExample() = 
    let brick = Brick(BluetoothCommunication("COM3"))
    do brick.Changed
       |> Observable.filter (fun e -> ...)
       |> Observable.add (fun e ->
           // some logic goes here...
       )
Tomas Petricek
  • 240,744
  • 19
  • 378
  • 553
  • 2
    It was also recently discussed here that subscribing to events is not thread-safe: http://stackoverflow.com/questions/35109354/using-f-event-in-multi-threaded-code – Fyodor Soikin Feb 01 '16 at 23:29