Get State from a GenServer process in Elixir

Kevin GathukuKevin Gathuku
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

0
Subscribe to my newsletter

Read articles from Kevin Gathuku directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Kevin Gathuku
Kevin Gathuku

I'm a web-focused developer with a passion for exploring new ideas and hopefully sharing more of them through this blog ๐Ÿ˜ƒ