When the Supervisor code below is invoked I expect the GenServer to start. The GenServer does not start and I want to know why and how to fix it.
defmodule App.Service do
use GenServer
def start_link(state) do
GenServer.start_link(__MODULE__, state)
end
def init(state) do
{:ok, state}
end
def get_state(pid) do
GenServer.call(pid, :get_state)
end
def set_state(pid,state) do
GenServer.call(pid, {:set_state, state})
end
def handle_call(:get_state, _from, state) do
{:reply, state, state}
end
def handle_call({:set_state, new_state}, _from, state)do
{:reply,state,[new_state | state]}
end
end
defmodule App.Supervisor do
use Supervisor
def start do
Supervisor.start_link(__MODULE__, [])
end
def init(_) do
children = [
App.Service
]
Supervisor.init(children, strategy: :one_for_one)
end
end
x = App.Supervisor.start()
IO.inspect x
pid = Process.whereis(App.Service)
# The following is nil. I expect a PID
IO.inspect pid
If you want to register a GenServer under a name, you should pass the
nameexplicitly tostart_link/3as explained here.In your case, the genserver was started but as an anonymous process.