我的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
Run Code Online (Sandbox Code Playgroud)
{: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]}]
]
]}
Run Code Online (Sandbox Code Playgroud)
我想返回[:code, :hello, :world]时,我叫GenServer.call(pid, :pop)我怎样才能做到这一点?
更改
@impl true
def handle_call(:pop, _from, [state]) do
{:reply, [state]}
end
Run Code Online (Sandbox Code Playgroud)
至
@impl true
def handle_call(:pop, _from, [state]) do
{:reply, state, []}
end
Run Code Online (Sandbox Code Playgroud)
您基本上返回状态并将当前状态设置为空列表
handle_call/3 以格式返回元组
{:reply, reply, new_state}
在您的情况下,您想要回复当前状态并将新状态设置为空列表.
{:reply, state, []}
或者如果要在不重置堆栈的情况下返回当前状态
{:reply, state, state}
| 归档时间: |
|
| 查看次数: |
50 次 |
| 最近记录: |