Does Elixir provide an easier way to get a GenServer process's current state?
Asked Answered
M

1

28

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?

Macknair answered 19/8, 2016 at 6:9 Comment(0)
S
47

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}
Secretin answered 19/8, 2016 at 6:11 Comment(1)
Thank you! How I missed that in the documentation!Macknair

© 2022 - 2024 — McMap. All rights reserved.