Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 254
sbs Avatar asked Aug 19 '16 06:08

sbs


People also ask

What is a GenServer Elixir?

A GenServer is a process like any other Elixir process and it can be used to keep state, execute code asynchronously and so on.

How GenServer works?

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.


1 Answers

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} 
like image 142
Dogbert Avatar answered Sep 21 '22 03:09

Dogbert