Skip to content

Commit

Permalink
use GenServer for Counter p204
Browse files Browse the repository at this point in the history
  • Loading branch information
dharnitski committed Sep 29, 2016
1 parent 38a5d79 commit 3b76168
Showing 1 changed file with 15 additions and 19 deletions.
34 changes: 15 additions & 19 deletions lib/rumbl/counter.ex
@@ -1,34 +1,30 @@
defmodule Rumbl.Counter do
use GenServer

def inc(pid), do: send(pid, :inc)
def inc(pid), do: GenServer.cast(pid, :inc)

def dec(pid), do: send(pid, :dec)
def dec(pid), do: GenServer.cast(pid, :dec)

def val(pid, timeout \\ 5000) do
ref = make_ref()
send(pid, {:val, self(), ref})
receive do
{^ref, val} -> val
after timeout -> exit(:timeout)
end
def val(pid) do
GenServer.call(pid, :val)
end

def start_link(initial_val) do
{:ok, spawn_link(fn -> listen(initial_val) end)}
GenServer.start_link(__MODULE__, initial_val)
end

def init(initial_val) do
Process.send_after(self, :tick, 1000)
{:ok, initial_val}
end

defp listen(val) do
receive do
:inc -> listen(val + 1)
:dec -> listen(val - 1)
{:val, sender, ref} ->
send sender, {ref, val}
listen(val)
end
def handle_cast(:inc, val) do
{:noreply, val + 1}
end
def handle_cast(:dec, val) do
{:noreply, val - 1}
end

def handle_call(:val, _from, val) do
{:reply, val, val}
end
end

0 comments on commit 3b76168

Please sign in to comment.