Skip to content

Instantly share code, notes, and snippets.

@hsavit1
Created July 28, 2016 22:38
Show Gist options
  • Save hsavit1/1635551a456140872b095a317a8bfd73 to your computer and use it in GitHub Desktop.
Save hsavit1/1635551a456140872b095a317a8bfd73 to your computer and use it in GitHub Desktop.
Genserver Implementation
defmodule Server do
def start(callback_module, state \\ nil) do
parent = self
spawn fn ->
loop(callback_module, parent, state)
end
end
def loop(callback_module, parent, state) do
receive do
message ->
state = callback_module.handle_message(message, parent, state)
loop(callback_module, parent, state)
end
end
end
## And test
defmodule Speaker do
def handle_message({:say, msg}, _from, _state) do
IO.puts msg
end
def handle_message(_other, _from, _state) do
false
end
end
server = Server.start(Speaker)
send server, {:say, "Hello world!"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment