Last active
April 29, 2020 16:34
-
-
Save ripzery/ef10a08128c8e616c4610c9862caac49 to your computer and use it in GitHub Desktop.
Counter Example to demonstrate GenServer from Programming Phoenix 1.4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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