Elixir OTP 初探(玩玩 call / cast)

Elixir 最為人使用的就是 OTP 的方式,很方便使用,如果需要多功的情況下(e.g. Spider 架構..)就非常好用

GenServer 使用的條件

handle_call(tuple, from, state): handle_call 只吃三個參數,返回值格式 {:reply, data, state} 此為固定的格式,但吐回 data 值

handle_cast(tuple, from, state): handle_cast 吃二個參數,返回值格式 {:reply, state},吐回 :ok

demo code 示範如下

defmodule Otp do
use GenServer
  def init(state) do
    {:ok, state}
  end
  # API(語法糖系列)
  def start_link(state) do
    {:ok, state}
  end
  def what-is-your-command(pid, value) do
    GenServer.call(pid, {what-is-your-command, value})
  end
  # Callback(handle系列)
  def handle_call({:what-is-your-command, value}, from, state) do
    {:reply, data, state} # return 值會拿到 data
  end
  def handle_cast({:what-is-your-command, value}, state) do
    {:reply, state} # return 值會拿到 :ok
  end
end
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.