Skip to content

Instantly share code, notes, and snippets.

@suhanlee
Last active March 24, 2018 14:20
Show Gist options
  • Save suhanlee/9634652c9c3447be6fce06f3b0b5f7de to your computer and use it in GitHub Desktop.
Save suhanlee/9634652c9c3447be6fce06f3b0b5f7de to your computer and use it in GitHub Desktop.
generic server
defmodule KeyValueStore do
def start do
ServerProcess.start(KeyValueStore)
end
def put(pid, key, value) do
ServerProcess.call(pid, {:put, key, value})
end
def get(pid, key) do
ServerProcess.call(pid, {:get, key})
end
def init do
HashDict.new
end
def handle_call({:put, key, value}, state) do
{:ok, HashDict.put(state, key, value)}
end
def handle_call({:get, key}, state) do
{HashDict.get(state, key), state}
end
end
defmodule ServerProcess do
def start(callback_module) do
spawn(fn ->
initial_state = callback_module.init
loop(callback_module, initial_state)
end)
end
def call(server_pid, request) do
send(server_pid, {:call, request, self})
receive do
{:response, response) ->
response
end
end
def cast(server_pid, request) do
send(server_pid, {:cast, request})
end
defp loop(callback_module, current_state) do
receive do
{:call, request, caller} ->
{response, new_state} = callback_module.handle_call(
request,
current_state
)
send(caller, {:response, response})
loop(callback_module, new_state)
{:cast, request} ->
new_state = callback_module.handle_cast(
request,
current_state
)
loop(callback_module, new_state)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment