Chapter 12. Getting Started with OTP

In order to help me understand how the GenServer behavior works, I drew the diagram shown in ???.

Processing a call in GenServer
Figure 12-1. Processing a call in GenServer

The client does a GenServer.call(server, request). The server will then call the handle_call/3 function that you have provided in the Module that you told GenServer to use. GenServer will send your module the client’s request, an identifier telling who the request is from, and the server’s current state.

Your handle_call/3 function will fulfill the client’s request and send a {:reply, reply, new_state} tuple back to the server. It, in turn, will send the reply back to the client, and use the new_state to update its state.

In Introducing Elixir and in the next two études, the client is you, using the shell. The module that handles the client’s call is contained within the same module as the GenServer framework, but, as the preceding diagram shows, it does not have to be.

Étude 12-1: Get the Weather

In this étude, you will create a weather server using the GenServer OTP behavior.This server will handle requests using a four-letter weather station identifier and will return a brief summary of the weather. You may also ask the server for a list of most recently accessed weather stations. The name of your module will be Weather.

Here is some sample output, with lines reformatted for ease of reading.

iex(1)> c("weather.ex") ...

Get Études for Elixir 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.