Skip to content

Instantly share code, notes, and snippets.

@thiagoa
Last active April 4, 2017 03:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thiagoa/c0356398ed59d125575b681d488b56ed to your computer and use it in GitHub Desktop.
Save thiagoa/c0356398ed59d125575b681d488b56ed to your computer and use it in GitHub Desktop.
defmodule Hub do
use GenServer
def start_link(options \\ []) do
GenServer.start_link(__MODULE__, :ok, options)
end
def init(:ok) do
{:ok, []}
end
def publish(hub, term) do
GenServer.cast(hub, {:publish, term})
end
defmacro subscribe(pid, pattern, do: block) do
quote do
Hub.do_subscribe unquote(pid)
receive do
{_, term} ->
case term do
unquote(pattern) -> unquote(block)
_ -> nil
end
end
end
end
def do_subscribe(hub, pid \\ self()) do
GenServer.call(hub, {:subscribe, pid})
end
def handle_call({:subscribe, pid}, _from, subscribers) do
{:reply, :ok, [pid | subscribers]}
end
def handle_cast({:publish, term}, subscribers) do
Enum.each subscribers, &(send(&1, {&1, term}))
{:noreply, subscribers}
end
end
defmodule Subscriber do
require Hub
def subscribe do
Hub.subscribe(:hub, %{signal_strength: strength} when strength < 5) do
IO.puts "Received message!"
end
end
end
Hub.start_link(name: :hub)
spawn fn ->
Subscriber.subscribe
end
spawn fn ->
Hub.publish(:hub, %{signal_strength: 4})
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment