Skip to content

Instantly share code, notes, and snippets.

@uri
Created October 25, 2017 03:02
Show Gist options
  • Save uri/07b91c9bc0a6761c579a8266ffb6f374 to your computer and use it in GitHub Desktop.
Save uri/07b91c9bc0a6761c579a8266ffb6f374 to your computer and use it in GitHub Desktop.
An example of the actor pattern in Elixir.
@moduledoc """
This file showcases how the actor pattern works in elixir by using send/receive
to pass messages and spawn to create a separate state for an actor.
import ActorTutorial
Create a tally actor and send a message
tally = start_tally()
send tally, {:add, 5}
send tally, {:add, 3}
send tally, {:query, self()}
By sending a message to `self()` we send a message to our own inbox. It can be
received with the blocking `receive` keyword:
receive do message -> IO.puts(message)
We can also start another process that can be responsible for printing out the
messages:
listener = start_listener()
send tally, {:query, listener}
send tally, {:add, 300}
send tally, {query, listener}
"""
defmodule ActorTutorial do
def start_tally do
spawn_link fn ->
tally(0)
end
end
def start_listener do
spawn_link fn ->
listener_display()
end
end
defp tally(current) do
receive do
{:add, addition} -> tally(current + addition)
{:query, to_inform} ->
send(to_inform, current)
tally(current)
_else -> tally(current)
end
end
defp listener_display() do
receive do
a ->
IO.puts(a)
listener_display()
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment