我是 Elixir 的初学者,我正在尝试了解如何使用 GenServer。对我来说神奇的是:
defmodule Stack do
use GenServer
# Callbacks
def handle_call(:pop, _from, [h|t]) do
{:reply, h, t}
end
def handle_cast({:push, item}, state) do
{:noreply, [item|state]}
end
end
代码取自 GenServer 文档。为什么回调函数返回{:reply, h, t}
时call
函数只返回一个值?
#Start the server
{:ok, pid} = GenServer.start_link(Stack, [:hello])
# This is the client
GenServer.call(pid, :pop)
#=> :hello #<<<<Why?
{:reply, h, t}
不是返回值吗?
最佳答案
Is
{:reply, h, t}
not a returned value?
{:reply, h, t}
是 handle_call
的返回值,但您没有调用该函数。您正在调用 GenServer.call
,它在内部调用 handle_call
,向其传递消息、调用者和当前状态,并且如果 handle_call
返回{:reply, a, b}
的 3 元组,它将第二个参数(在本例中为 a
)发送回调用者,并将其状态更改为 b
.
关于elixir - GenServer中的回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36982614/