Skip to content

Instantly share code, notes, and snippets.

@rozap
Created February 22, 2016 17:54
Show Gist options
  • Save rozap/257a09a55b4293abd594 to your computer and use it in GitHub Desktop.
Save rozap/257a09a55b4293abd594 to your computer and use it in GitHub Desktop.
defmodule KVStore do
use GenServer
# This executes within the supervisor or whoever starts the KVStore
def start_link do
# First arg is the callback module (this module)
# The name arg registers the process globally as `KVStore`, essentially making it a singleton
GenServer.start_link(KVStore, [], name: KVStore)
end
##
# These next 3 functions execute within the calling process
# callback called when the process starts up
def init(_) do
state = %{} # state is just an empty dictionary
{:ok, state}
end
def handle_call({:add, key, value}, _from, state) do
new_state = Map.put(state, key, value)
{:reply, :ok, new_state}
end
def handle_call({:get, key}, _from, state) do
# state doesn't change here, just give back the value
{:reply, state[key], state}
end
## These next two functions execute within the calling process, and are provided
# as an interface. They're not required, but it's idiomatic to provide "interface functions"
# in your genserver/genevent/etc so that callers don't need to know the structure of the message
# that is passed, they just need to know how to call a function
def push(key, value) do
# This sends the message. Anything sending a message accepts either a pid or a name associated with a pid. Since
# the process registered itself as `KVStore` on startup, we can use KVStore here as the associated name
GenServer.call(KVStore, {:push, key, value)
end
def get(key) do
GenServer.call(KVStore, {:get, key})
end
end
@rozap
Copy link
Author

rozap commented Feb 22, 2016

So then you could do

KVStore.put(:foo, 1)
KVStore.get(:foo)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment