Anatomy of a GenServer

In the last chapter, we built a basic calculator, with and without a GenServer. Let’s look back at that program. We’ll focus on a a couple major messages: add and state:

 def​ start(initial_state) ​do
  spawn(​fn​ -> run(initial_state) ​end​)
 end
 
 def​ run(state) ​do
  state
  |> listen
  |> run
 end
 
 def​ listen(state) ​do
 receive​ ​do
  {​:add​, number} ->
  Core.add(state, number)
 
  {​:state​, pid} ->
  send(pid, {​:state​, state})
  state
 end
 end

This program has the same basic shape of many other Elixir programs. There are two major parts, the lifecycle management and the message process. Our lifecycle management is a simple start function to start a process. The run and listen messages ...

Get Programmer Passport: OTP 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.