Given a 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 process state 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 is there an easier way provided by Elixir to get a GenServer
process's current state?
A GenServer is a process like any other Elixir process and it can be used to keep state, execute code asynchronously and so on.
A GenServer is implemented in two parts: the client API and the server callbacks. You can either combine both parts into a single module or you can separate them into a client module and a server module. The client is any process that invokes the client function.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With