Strange behaviour or DynamicSupervisor

I’m a bit confused on how to start children under a DynamicSupervisor in my app.
Basically I need to have n distinct DynamicSupervisor which I start children under them via their pid.
However, following the DynamicSupervisor doc I find a strange behaviour:

children = [
 {DynamicSupervisor, strategy: :one_for_one, name: MyApp.DynamicSupervisor}
 ]

{:ok, sup} = Supervisor.start_link(children, strategy: :one_for_one)

{:ok, #PID<0.289.0>}

{:ok, child} = DynamicSupervisor.start_child(sup, {Agent, fn -> 1 end})

** (MatchError) no match of right hand side value: {:error, {:invalid_child_spec, {{Agent, :start_link, [#Function<45.79398840/0 in :erl_eval.expr/5>]}, :permanent, 5000, :worker, [Agent]}}}

Returns :invalid_child_spec, while using the Atom instead of the pid is fine.

{:ok, child} = DynamicSupervisor.start_child(MyApp.DynamicSupervisor, {Agent, fn -> 1 end})

{:ok, #PID<0.295.0>}

Why is this the case?
The type signature of the start_child/2 function requires a supervisor() as first argument which can be a pid().

What am i missing?

Thanks

In your snippet, sup is the pid of the Supervisor that started the DynamicSupervisor, but not DynamicSupervisor itself.

Try this instead:

iex(1)> {:ok, sup} = DynamicSupervisor.start_link(strategy: :one_for_one)
iex(2)> {:ok, pid} = DynamicSupervisor.start_child(sup, {Agent, fn -> 1 end})
1 Like

Thank you!
I was a bit confused!
The thing that made me focus on the wrong thing was the error message…