GenServer 中的回调函数
Callbacks function in GenServer
我是 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 文档。为什么 call
函数只有 return 一个值,然后回调函数 returns {:reply, h, t}
?
#Start the server
{:ok, pid} = GenServer.start_link(Stack, [:hello])
# This is the client
GenServer.call(pid, :pop)
#=> :hello #<<<<Why?
{:reply, h, t}
不是 returned 值吗?
Is {:reply, h, t}
not a returned value?
{:reply, h, t}
是 handle_call
的 return 值,但您并未调用该函数。您正在调用 GenServer.call
,它在内部调用 handle_call
,将消息、调用者和当前状态传递给它,如果 handle_call
return 是 [=16 的 3 元组=],它将第二个参数,在本例中为 a
发送回调用者,并将其状态更改为 b
.
我是 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 文档。为什么 call
函数只有 return 一个值,然后回调函数 returns {:reply, h, t}
?
#Start the server
{:ok, pid} = GenServer.start_link(Stack, [:hello])
# This is the client
GenServer.call(pid, :pop)
#=> :hello #<<<<Why?
{:reply, h, t}
不是 returned 值吗?
Is
{:reply, h, t}
not a returned value?
{:reply, h, t}
是 handle_call
的 return 值,但您并未调用该函数。您正在调用 GenServer.call
,它在内部调用 handle_call
,将消息、调用者和当前状态传递给它,如果 handle_call
return 是 [=16 的 3 元组=],它将第二个参数,在本例中为 a
发送回调用者,并将其状态更改为 b
.