Retrieve all state from GenServer

时间:2018-10-14 14:22:55

标签: elixir

I have a an array of atoms for state in my GenServer. I don't want to just pop off the the last item in the queue, I want to pop off all the state at once.

Current Code (NOT WORKING)

defmodule ScoreTableQueue do
  use GenServer

  @impl true
  def init(stack) do
    {:ok, stack}
  end

  @impl true
  def handle_call(:pop, _from, [state]) do
    {:reply, [state]}
  end

  @impl true
  def handle_cast({:push, item}, state) do
    {:noreply, [item | state]}
  end
end

State of GenServer:

{:status, #PID<0.393.0>, {:module, :gen_server},
 [
   [
     "$initial_call": {ScoreTableQueue, :init, 1},
     "$ancestors": [#PID<0.383.0>, #PID<0.74.0>]
   ],
   :running,
   #PID<0.393.0>,
   [],
   [
     header: 'Status for generic server <0.393.0>',
     data: [
       {'Status', :running},
       {'Parent', #PID<0.393.0>},
       {'Logged events', []}
     ],
     data: [{'State', [:code, :hello, :world]}]
   ]
 ]}

I'm want to return [:code, :hello, :world] when I call GenServer.call(pid, :pop) How can I accomplish this?

1 个答案:

答案 0 :(得分:5)

更改

@impl true
def handle_call(:pop, _from, [state]) do
  {:reply, [state]}
end

 @impl true
 def handle_call(:pop, _from, [state]) do
  {:reply, state, []}
 end

您基本上是在返回状态并将当前状态设置为空列表

handle_call/3返回格式为

的元组

{:reply, reply, new_state}

在您的情况下,您想回复当前状态并将新状态设置为空列表。

{:reply, state, []}

或者如果您想返回当前状态而不重置堆栈

{:reply, state, state}