skip to content
Lean Miguel

GenServer Basics

/ 2 min read

GenServer Intro

A GenServer process manages state and loops indefinitely until stopped. Elixir provides a module for implementing a GenServer process. To use the GenServer module, you need to implement its behavior. The main functions that a GenServer needs to implement are

init(init_arg)

The init function sets off the initial state for your process. init should return {:ok, state} to start the GenServer process loop.

handle_call

handle_call is used when you want to grab values from the GenServer state. handle_call should return {:reply, reply, new_state} when you want to send a reply back to the user.

handle_cast

handle_cast is used when you want to update the state inside the GenServer. handle_cast should return {:noreply, new_state} to continue the GenServer process loop.

handle_info

handle_info is used when you want to send messages to the GenServer process that aren’t handled by handle_call or handle_cast. handle_info can be used to send messages from within the GenServer callbacks. handle_info should return {:noreply, new_state} to continue the GenServer process loop.

GenServer Practice

To further grasp usage of GenServers, implement the following modules

Counter
defmodule Counter do
	use GenServer
	
	@impl true
	def init(init_arg) do

	end
	
	@impl true
	def handle_cast(:increment, state) do
	end
	
	@impl true
	def handle_cast(:decrement, state) do
	
	end
	
	@impl true
	def handle_call(:get, _from, state) do
	
	end
end
Key Value Store
defmodule KeyValue do
  use GenServer

  @impl true
  def init(init_arg) do # consider adding a guard here
    
  end

  @impl true
  def handle_call({:get, ...}, _from, state) do
    
  end

  @impl true
  def handle_cast({:set, key, value}, state) do
    
  end

  def handle_cast({:delete, key}, state) do
    
  end
end
Cache
defmodule Cache do
  use GenServer

  def init(_init_arg) do
    
  end

  def handle_call({:get, key}, _from, state) do
    
  end

  def handle_cast({:put, key, value, ttl}, state) do
  
  end
  
  def handle_info({:ttl_delete, key}, state) do
    
  end
end

GenServer Documentation

GenServer Callbacks