Running multiple instances of the same event handler in Elixir

I have a simple event handler in elixir using GenEvent:

defmodule myHandler do
    use GenEvent
    #Callback
    def handle_event {:message, x}, state do
        IO.puts("Message value is #{x}")
        {:ok, [x|state]}
    end
end

I can start one handler and manager in the usual way:

{:ok, mgr} = GenEvent.start_link

myServer.start_link(mgr)

GenEvent.add_handler(mgr,myHandler, [])

However, I would like to start a control tree where there are N handlers, each with a different identifier, using the same manager.

I tried:

Gen.Event.add_handler({mgr, :id1},myHandler, [])

bad luck! Instead, I get the following error:

** (Mix) Could not start application : exited in: myApp.start(:normal, [])
** (EXIT) no connection to :id1

I am new to Elixir, so I struggle a bit with the documentation. I would be grateful if someone would show me how to do this! Thanks.

+4
source share
2 answers

You can always have a more complex state in MyHandler:

defmodule MyHandler do
  use GenEvent

  def handle_event({:message, id, message}, {id, messages}) do
    IO.puts "[ID: #{inspect id}] Message value is #{inspect message}."
    {:ok, {id, [message | messages]}}
  end

  def handle_event(_, state) do
    {:ok, state}
  end
end

id, :

{:message, id, message}

, . , .

, id, - :

{:ok, manager} = GenEvent.start_link
MyServer.start_link manager
GenEvent.add_handler manager, MyHandler, {id, []}

, {id :: atom, messages :: list} .

:

GenServer.sync_notify manager, {:message, id, message}

:

:

iex(1)>  {:ok, manager} = GenEvent.start_link
{:ok, #PID<0.75.0>}

:

iex(2)> GenEvent.add_handler manager, MyHandler, {:id0, []}
:ok

:id0 :

iex(3)> GenEvent.sync_notify manager, {:message, :id0, "Hello"} 
[ID: :id0] Message value is "Hello".
:ok

:id1 :

iex(4)> GenEvent.sync_notify manager, {:message, :id1, "Hello"}
:ok

. , :)

P.S: , map:

%{id: id, messages: []}
+4

, , - :

GenEvent.add_handler(:myManager, {myHandler, :id1}, [])

, - @true_droid Elixir slack.

+4

Source: https://habr.com/ru/post/1620759/


All Articles