Skip to content

Instantly share code, notes, and snippets.

@jurvis jurvis/shoppinglist_example.ex Secret
Created Jun 22, 2019

Embed
What would you like to do?
Simple GenServer Application
defmodule GenServerExample.ShoppingList do
use GenServer
# Client Methods
#
def start_link(opts \\ []) do
GenServer.start_link(__MODULE__, :ok, opts)
end
def add(pid, name) do
GenServer.cast(pid, {:add, name})
end
def remove(pid, name) do
GenServer.cast(pid, {:remove, name})
end
def print(pid) do
GenServer.call(pid, :print)
end
# Server Methods
#
def init (:ok) do
{:ok, []}
end
def handle_cast({:add, name}, shopping_list) do
new_shopping_list = [name | shopping_list]
{:noreply, new_shopping_list}
end
def handle_cast({:remove, name}, shopping_list) do
new_shopping_list = List.delete(shopping_list, name)
{:noreply, new_shopping_list}
end
def handle_call(:print, _from , shopping_list) do
{:reply, shopping_list, shopping_list}
end
# Helper Methods
#
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.