liveBook · Manning

GenServer.start/2

As explained in Elixir in Action, Third Edition

GenServer.start is an Elixir API function that starts a GenServer process from a callback module and initialization argument.

GenServer.start/2 creates a GenServer-powered process from a callback module and passes its second argument to init/1. It returns {:ok, pid} after initialization completes. section 6.2.2 section 6.2.3

A typical GenServer.start/2 integration includes:

  • Define a module with use GenServer and implement init/1, handle_cast/2, and handle_call/3. section 6.2.3
  • Wrap GenServer.start(KeyValueStore, nil) in a module-specific start function when exposing a simpler interface. section 6.2.2 section 6.2.3
  • Use the returned PID with GenServer.cast/2 and GenServer.call/2 to issue requests handled in the server process. section 6.2.3 section 6.2.6

Starting a key-value server

{:ok, pid} = GenServer.start(KeyValueStore, nil) GenServer.cast(pid, {:put, :some_key, :some_value}) GenServer.call(pid, {:get, :some_key}) # => :some_value section 6.2.2 section 6.2.3

iex(3)> GenServer.start(KeyValueStore, nil)
{:ok, #PID<0.51.0>}

Inspect the minimal shell invocation and the {:ok, pid} result. section 6.2.2

How Elixir in Action, Third Edition covers it

How deep it goes
Explains callback wiring, initialization arguments, return values, blocking until init/1 finishes, and the resulting process lifecycle.
Examples
Uses a KeyValueStore process that starts with an empty map and handles put and get requests.
What it assumes
Assumes familiarity with Elixir modules and processes while teaching callback-based server initialization from the startup call onward.
What you can do after
Operate a GenServer by starting its callback module, retaining its PID, and sending requests through GenServer.call/2 or GenServer.cast/2.
How it connects
Connects GenServer.start/2 with GenServer behavior, init/1, handle_call/3, handle_cast/2, GenServer.call/2, and GenServer.cast/2.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Elixir in Action, Third Edition. The section links point to the parts of the book it draws on.