geoffrey91
geoffrey91

Reputation: 89

Event.Trigger Event.Publish f#

Reading code about the creation of new events in f# i've encountered the two calls event.Publish and event.Trigger, but i'm not quite sure about their meaning. Could you explain to me what they do?

Keep in consideration what's written in the manual: event.Publish Publishes an observation as a first class value. event.Trigger Triggers an observation using the given parameters.

Since i'm Italian the term "observation" used in this context doesn't do me any good.

Upvotes: 7

Views: 791

Answers (2)

Tomas Petricek
Tomas Petricek

Reputation: 243096

The typical pattern when implementing a new F# type that exposes an event is to create the event value as a local field, trigger the event using event.Trigger somewhere in the code and expose it to users of your type using trigger.Publish:

type Counter() =
  // Create the `Event` object that represents our event
  let event = new Event<_>()
  let mutable count = 0
  member x.Increment() =
    count <- count + 1
    if count > 100 then 
      // Trigger the event when count goes over 100. To keep the sample
      // simple, we pass 'count' to the listeners of the event.
      event.Trigger(count)
  // Expose the event so that the users of our type can register event handlers
  [<CLIEvent>]
  member x.LimitReached = event.Publish

The CLIEvent attribute on the published member is optional, but it is good to know about it. It says that the member will be compiled to a .NET event (and C# will see it as event). If you do not add it, then F# exposes it just as a member of type IEvent (which is fine for F# use).

Upvotes: 7

muratgu
muratgu

Reputation: 7311

It's explained here very well.

In short, think of event.Publish as a way to expose the event, so that clients can subscribe to by calling the Add function. event.Trigger raises the actual event.

Upvotes: 4

Related Questions