Skip to Main Content
Programming Phoenix
book

Programming Phoenix

by Chris McCord, Bruce Tate, Jose Valim
April 2016
Beginner to intermediate content levelBeginner to intermediate
300 pages
6h 58m
English
Pragmatic Bookshelf
Content preview from Programming Phoenix

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming Elm

Programming Elm

Jeremy Fairbank
Real-Time Phoenix

Real-Time Phoenix

Stephen Bussey

Publisher Resources

ISBN: 9781680501926Errata Page