GenServer
Get introduced to GenServers, which are usually considered the fundamental abstraction in OTP, and learn how to test GenServers.
A GenServer is a process that holds state and optionally provides an interface to read or update that state.
OTP abstracts all of the common parts of a GenServer, like spawning the process, having a receive loop, and sending messages. What’s left to the user is to implement callbacks that implement code specific to a particular GenServer.
Initializing a GenServer
We’ll see how we can use a GenServer in the Soggy Waffle application, but let’s start with a self-contained example, which will make things easier when illustrating some concepts.
We’ll use a GenServer that provides a simple rolling average of the last N numeric measurements. We can start with a simple implementation by looking at the public API exposed by the GenServer:
#file path -> example/lib/overloaded_genserver.ex#add this code at the indicated place mentioned in comments of example/lib/#overloaded_genserver.ex in the playground widgetdef start_link(max_measurements) doGenServer.start_link(__MODULE__, max_measurements)enddef add_element(pid, element) doGenServer.cast(pid, {:add_element, element})enddef average(pid) doGenServer.call(pid, :average)end
We have a function to start the GenServer, a function to store a new element in the GenServer, and a function to get the average of the elements that the GenServer is storing at a given time. From the public API, we know that this is going to be a GenServer (because of the calls ...