Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# remove function handler

Tags:

.net

events

f#

So, I have a function that I want to execute on an event trigger, but I want to remove it later. What do I do for this? I know that F# events have the Add method that adds a function as a handler, but you can't remove this function. I understand, but I can't find how to create any delegate at all! (Well, there is the type Foo = delegate of type1 -> type2, but I don't understand its usage...)

EDIT: Here's a more clear example of what I want to do, in code:

// Define and publish event
let _someEvent = new Event<string>()
let SomeEvent = someEvent.Publish

// Normally, I'd do this to use it:
SomeEvent.Add (fun arg -> printfn "Argument: %s" arg)

// Trigger the event
someEvent.Trigger "Hello world"

But my problem is that I want to remove this hook sometime. I know that its possible with delegates... just don't know precisely how to do it.

like image 544
Jwosty Avatar asked Jan 26 '13 03:01

Jwosty


1 Answers

Another option is to use the Subscribe method and unsubscribe using Dispose:

// Define and publish event
let someEvent = new Event<string>()
let SomeEvent = someEvent.Publish

// Subscribe to event
let subscription =
    SomeEvent.Subscribe (fun arg -> printfn "Argument: %s" arg)

// Trigger the event
someEvent.Trigger "Hello world"

// Unsubscribe
subscription.Dispose()
like image 140
Phillip Trelford Avatar answered Oct 02 '22 14:10

Phillip Trelford