Does Elixir provide an easier way to get the current state of a GenServer process?

Given the simple GenServer process.

 defmodule KVServer do use GenServer def start do GenServer.start(__MODULE__, %{}, name: :kv_server) end def store(k, v) do GenServer.cast(:kv_server, {:store, k, v}) end def handle_cast({:store, k, v}, state) do {:noreply, Map.put(state, k, v)} end end 

I can get the current state of the process using :sys.get_status/1

 iex(1)> {:ok, pid} = KVServer.start {:ok, #PID<0.119.0>} iex(2)> KVServer.store(:a, 1) :ok iex(3)> KVServer.store(:b, 2) :ok iex(4)> {_,_,_,[_,_,_,_,[_,_,{_,[{_,state}]}]]} = :sys.get_status(pid) ... iex(5)> state %{a: 1, b: 2} 

Just wondering if there is an easier way that Elixir provides to get the current state of the GenServer process?

+7
elixir gen-server
source share
1 answer

Use :sys.get_state/1 :

 iex(1)> {:ok, pid} = KVServer.start {:ok, #PID<0.86.0>} iex(2)> KVServer.store(:a, 1) :ok iex(3)> KVServer.store(:b, 2) :ok iex(4)> :sys.get_state(pid) %{a: 1, b: 2} 
+15
source share

All Articles