首页 > 解决方案 > 从 GenServer 检索所有状态

问题描述

我的 GenServer 中有一个状态原子数组。我不想只弹出队列中的最后一项,我想一次弹出所有状态。

当前代码(不工作)

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

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]}]
   ]
 ]}

我想[:code, :hello, :world]在我打电话时返回GenServer.call(pid, :pop)我该如何做到这一点?

标签: elixir

解决方案


改变

@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}


推荐阅读