【问题标题】:Initializing GenServer state with more than one thing用不止一件事初始化 GenServer 状态
【发布时间】:2018-04-04 18:41:05
【问题描述】:

我想创建一个一开始就需要多个状态的 GenServer。特别是init 函数启动了一个需要知道一些初始状态的计时器。我知道GenServer.start_link的第二个参数直接传递给init(arg)

但是我找不到一个示例来说明如何在init 中传递多个状态参数以进行初始化。例如,需要的东西是:

defmodule Application.Test do
  require GenServer

  def start_link(state1, state2) do 
    GenServer.start_link(__MODULE__, [state1, state2], [])
  end 

  def init(state) do
    # Use the state to launch timer
  end
end

但是,因为我不能 找不到一个例子,而且我对长生不老药真的很陌生,这对我来说似乎并不习惯。有没有更好/更有效的方法来做到这一点,或者这是最好的方法?

【问题讨论】:

    标签: elixir state erlang-otp


    【解决方案1】:

    只需将您的状态包装在 TupleStruct 中,如下所示:

    start_link(state1, state2) do
      Genserver.start_link(__MODULE__, {state1, state2}, [])
    end
    
    # use pattern matching to extract the states
    def init({state1, state2}) do
      # use state1 and state2
    end
    

    【讨论】:

    • 我更喜欢使用 map - tuple 不是最好的选择,当你想编辑它时,也是 struct,因为你不能添加新的键。
    • 当然你可以使用最适合这种情况的任何东西 - 我在这里只使用了一个元组,因为在示例中只有 2 个变量要包装。
    猜你喜欢
    • 2015-01-17
    • 2018-02-19
    • 2019-05-08
    • 2017-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多