Add example of process as state

This commit is contained in:
Jay Hayes
2016-05-03 19:05:35 -05:00
parent 6126d5a836
commit 65b9af48b4
2 changed files with 29 additions and 0 deletions

View File

@@ -82,6 +82,34 @@ defmodule Processes do
Process.exit(pid, :kill) Process.exit(pid, :kill)
end end
def state(value) do
receive do
{caller, :get} ->
send caller, value
state(value)
{caller, :set, new_value} ->
state(new_value)
end
end
koan "Processes can be used to hold state" do
initial_state = "foo"
pid = spawn fn ->
state(initial_state)
end
send pid, {self, :get}
receive do
value -> assert value == ___
end
send pid, {self, :set, "bar"}
send pid, {self, :get}
receive do
value -> assert value == ___
end
end
koan "Waiting for a message can get boring" do koan "Waiting for a message can get boring" do
parent = self parent = self
spawn(fn -> receive do spawn(fn -> receive do

View File

@@ -13,6 +13,7 @@ defmodule ProcessesTests do
"hola!", "hola!",
:how_are_you?, :how_are_you?,
{:multiple, ["O", "HAI"]}, {:multiple, ["O", "HAI"]},
{:multiple, ["foo", "bar"]},
{:waited_too_long, "I am impatient"}, {:waited_too_long, "I am impatient"},
{:exited, :random_reason}, {:exited, :random_reason},
:normal, :normal,