O'Reilly logo

Programming Phoenix by Jose Valim, Bruce Tate, Chris McCord

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required