Created
April 22, 2016 13:53
-
-
Save octosteve/88ce5007c0eb951ed9b9940cd26aaac9 to your computer and use it in GitHub Desktop.
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 GenIncrement do | |
use GenServer | |
# Public | |
def start_link do | |
# GenServer.start_link(GenIncrement, [], name: __MODULE__) | |
{:ok, pid} = GenServer.start_link(GenIncrement, []) | |
Process.register(pid, __MODULE__) | |
{:ok, pid} | |
end | |
def increment do | |
GenServer.cast(__MODULE__, {:increment}) | |
end | |
def decrement do | |
GenServer.cast(__MODULE__, {:decrement}) | |
end | |
def reset do | |
GenServer.cast(__MODULE__, {:reset}) | |
end | |
def status do | |
GenServer.call(__MODULE__, {:status}) | |
end | |
# Private | |
def init(_) do | |
{:ok, 0} | |
end | |
def handle_cast({:increment}, total) do | |
{:noreply, total + 1} | |
end | |
def handle_cast({:decrement}, total) do | |
{:noreply, total - 1} | |
end | |
def handle_cast({:reset}, _total) do | |
{:noreply, 0} | |
end | |
def handle_call({:status}, _pid, total) do | |
reply_with = total | |
next_state = total | |
{:reply, reply_with, next_state} | |
end | |
end |
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 Increment do | |
def loop(total \\ 0) do | |
receive do | |
{:increment} -> loop(total + 1) | |
{:decrement} -> loop(total - 1) | |
{:reset} -> loop | |
{:status, pid} -> | |
send(pid, {:result, total}) | |
loop(total) | |
end | |
end | |
end |
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 ProcessTest do | |
def loop do | |
receive do | |
{:ok, msg} -> IO.puts("I got a message!!! #{msg}") | |
anything -> | |
IO.puts "I don't understand that" | |
IO.inspect anything | |
end | |
loop | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment