Get State from a GenServer process in Elixir

ยท

1 min read

TIL that I have been doing this completely wrong.

I have been using this custom implementation:

defmodule MyModule do
 use GenServer

  def report(server) do
    GenServer.call(server, :report)
  end

  # More functions

  @impl true
  def handle_call(:report, _from, state) do
    # No modifications. Return the current state
    {:reply, state, state}
  end
end

It is all good and it works. However, it turns out this is all I needed to do

{:ok, pid} = MyModule.start_link([])
# ... some more operations...
:sys.get_state(pid)

Well, it does say right there in the get_state docs that the whole purpose is to help the users not to reimplement it.

Now I know and so do you ๐Ÿ˜€

More resources:

https://hexdocs.pm/elixir/GenServer.html#module-debugging-with-the-sys-module

https://www.erlang.org/doc/man/sys.html#module