Created
February 22, 2016 17:54
-
-
Save rozap/257a09a55b4293abd594 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
So then you could do