Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.96 KB | None | 0 0
  1. # handle_info, handles
  2. # GenServer.call(pid, {:something, :key})
  3.  
  4. Notice that you didn’t use match-all clauses for handle_cast and handle_call in previous examples.
  5. This was intentional. Casts and calls are well-defined requests.
  6. They specify an interface between clients and the server process. Thus an invalid cast means your clients are using an unsupported interface. In such cases, you usually want to fail fast and signal an error.
  7.  
  8.  
  9. defmodule KeyValueStore do
  10. use GenServer
  11.  
  12. def init(_) do
  13. {:ok , %{}}
  14. end
  15.  
  16. def start do
  17. GenServer.start(KeyValueStore, nil)
  18. end
  19.  
  20. def put(pid, key, value) do
  21. GenServer.cast(pid, {:put, key, value})
  22. end
  23.  
  24. def get(pid, key) do
  25. GenServer.call(pid, {:get, key})
  26. end
  27.  
  28. def handle_cast({:put, key, value}, state) do
  29. { :noreply, Map.put(state, key, value) }
  30. end
  31.  
  32. def handle_call({:get, key}, state) do
  33. { :reply, Map.get(state, key) }
  34. end
  35.  
  36. def handle_info(_, state) do
  37. {:noreply, state}
  38. end
  39. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement