Add example of process as state
This commit is contained in:
@@ -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
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
Reference in New Issue
Block a user