user6467981
user6467981

Reputation:

Initializing GenServer state with more than one thing

I want to create a GenServer that requires more than one piece of state in the beginning. In particular the init function kicks off a timer that needs to know a few pieces of initial state. I understand that the second argument to GenServer.start_linkis passed directly into init(arg).

However I can't find an example that shows how to pass more than one argument of state in for initialization in init. For example something desirable would be:

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

However, since I can' t find an example, and I'm really new to elixir, this doesnt seem idiomatic to me. Is there a better/more efficient way to do this, or is this the best way?

Upvotes: 0

Views: 848

Answers (1)

Pfitz
Pfitz

Reputation: 7344

Just wrap your states in a Tuple or Struct like this:

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

Upvotes: 3

Related Questions