Skip to content

Instantly share code, notes, and snippets.

@ripzery
Last active April 29, 2020 16:34
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 ripzery/ef10a08128c8e616c4610c9862caac49 to your computer and use it in GitHub Desktop.
Save ripzery/ef10a08128c8e616c4610c9862caac49 to your computer and use it in GitHub Desktop.
Counter Example to demonstrate GenServer from Programming Phoenix 1.4
defmodule CounterService do
use GenServer
def inc(pid), do: GenServer.cast(pid, :inc)
def dec(pid), do: GenServer.cast(pid, :dec)
def val(pid) do
GenServer.call(pid, :val)
end
def start_link(initial_val) do
GenServer.start_link(__MODULE__, initial_val)
end
def init(initial_value) do
Process.send_after(self(), :tick, 1000)
{:ok, initial_value}
end
def handle_info(:tick, val) when val < 0, do: raise("Boom!")
def handle_info(:tick, val) do
IO.puts("Tick #{val}")
Process.send_after(self(), :tick, 1000)
{:noreply, val - 1}
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment