Managing State with Processes

Functional programs are stateless, but we still need to be able to manage state. In Elixir, we use concurrent processes and recursion to handle this task. That may sound counterintuitive, but let’s take a look at how it works with a simple program.

Let’s create a Counter server that counts up or down. Create a lib/rumbl/counter.ex file and key this in:

1: defmodule​ Rumbl.Counter ​do
def​ inc(pid), ​do​: send(pid, ​:inc​)
5: def​ dec(pid), ​do​: send(pid, ​:dec​)
def​ val(pid, timeout \\ 5000) ​do
ref = make_ref()
send(pid, {​:val​, self(), ref})
10: receive​ ​do
{^ref, val} -> val
after​ timeout -> ​exit​(​:timeout​)
end
end ...

Get Programming Phoenix now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.