【问题标题】:Retrieve all state from GenServer从 GenServer 检索所有状态
【发布时间】:2018-10-14 22:57:20
【问题描述】:

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

当我打电话给GenServer.call(pid, :pop) 时,我想返回[:code, :hello, :world] 我该怎么做?

【问题讨论】:

    标签: elixir


    【解决方案1】:

    改变

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

    【讨论】:

      猜你喜欢
      • 2017-09-29
      • 2015-01-17
      • 2018-08-18
      • 2016-01-29
      • 2021-08-01
      • 2021-02-15
      • 2012-08-01
      • 1970-01-01
      • 2015-07-28
      相关资源
      最近更新 更多