Skip to content

Instantly share code, notes, and snippets.

@Kociamber
Last active October 25, 2017 13:49
Show Gist options
  • Save Kociamber/cc10ce05a05ecf4f628e3d06e68bb5d4 to your computer and use it in GitHub Desktop.
Save Kociamber/cc10ce05a05ecf4f628e3d06e68bb5d4 to your computer and use it in GitHub Desktop.
Example implementation of Elixir GenServer and some nice comments.
defmodule ExampleGenServer do
use GenServer
## Client API
# Starts detached process of GenServer
def start_link do
# Fisrt arg is a GenServer's module name, second one is its initial state and/or its type
# Name of a process can be specified (name: :name) but it also prevents of running multiple process of the same type
GenServer.start_link(__MODULE__, [])
end
# Sample client call function. First arg is a PID, other are of course optional
def get_state(pid) do
# second one a tuple in format: {:some_call, arg1, arg2,...}
GenServer.call(pid, {:some_call})
end
# Sample client cast function. First arg is a PID, second one a tuple in format: {:some_cast, arg1, arg2,...}
def set_state(pid) do
GenServer.cast(pid, {:some_cast})
end
## Server API / Callbacks
# Purpose of this function is to return initial state in required format: {:ok, initial_state}
# If it will not store any state we can skip it
def init(initial_state) do
{:ok, initial_state}
end
# When called, all below callbacks get access to current GenServet process state and they are resetting the state while returning response
# Synchronous function which handles GenServer calls and returns reply tuple: {:reply, state, state}
def handle_call({:some_call}, _from, state) do
# stuff
return_value = "return value"
{:reply, return_value, state}
end
# Asynchronous function which handles GenServer casts and returns no-reply tuple: {:noreply, state}
def handle_cast({:some_cast}, state) do
# stuff
{:noreply, state}
end
# Asynchronous function which handles messages from abny other places (than GenServer) and returns no-reply tuple: {:noreply, state}
def handle_info({:some_info}, state) do
# stuff
{:noreply, state}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment