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 ...

Get Programming Phoenix now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.