GenEvent

From Elixir Wiki
Jump to navigation Jump to search

GenEvent[edit]

File:GenEvent.png
GenEvent Elixir

GenEvent is a behavior module in the Elixir programming language that allows for event-driven programming. With GenEvent, users can implement generic event handling modules that can be subscribed to by multiple processes.

Usage[edit]

To define and use a GenEvent module, the following steps can be followed:

1. First, define the behavior by using the `defmodule` directive with the `@behaviour` attribute:

```elixir defmodule MyEventModule do

 @behaviour GenEvent
 ...

end ```

2. Implement the callback functions required by the GenEvent behavior:

```elixir def handle_event(state, event, acc) do

 # handle the event
 ...
 {:ok, new_state}

end

def handle_call(state, event, acc) do

 # handle synchronous call
 ...
 {:reply, reply, new_state}

end ```

3. Create a GenEvent process by calling `GenEvent.start_link(module, args)`:

```elixir {:ok, pid} = GenEvent.start_link(MyEventModule, initial_state) ```

4. Subscribe interested processes to the GenEvent by using `GenEvent.add_handler`:

```elixir GenEvent.add_handler(pid, handler) ```

5. Trigger an event by invoking `GenEvent.notify`:

```elixir GenEvent.notify(pid, event) ```

Example[edit]

Here is an example that illustrates the usage of GenEvent:

```elixir defmodule MyEventModule do

 @behaviour GenEvent
 def handle_event(state, event, acc) do
   IO.puts("Handling event: #{event}")
   {:ok, state}
 end
 def handle_call(state, event, acc) do
   IO.puts("Handling synchronous call: #{event}")
   {:reply, event * 2, state}
 end

end

{:ok, pid} = GenEvent.start_link(MyEventModule, {}) GenEvent.add_handler(pid, self())

GenEvent.notify(pid, :my_event) reply = GenEvent.call(pid, :my_synchronous_event)

IO.puts("Received reply from event: #{reply}") ```

See Also[edit]

External Links[edit]