elixirgen-servererlang-supervisor

How to update from deprecated Supervisor.spec to new Supervisor.behaviour?


Background

I am trying to build a supervision tree in my app, where a given GenServer will have to supervise other GenServers. This is not an application, just a simple GenServer that needs to supervise others.

To achieve this I mainly focused my attention on the following article: http://codeloveandboards.com/blog/2016/03/20/supervising-multiple-genserver-processes/

Code

The above article led me to the following code:

defmodule A.Server do
  use Supervisor

  alias B

  def start_link, do:
    Supervisor.start_link(__MODULE__, nil, name: __MODULE__)

  def init(nil) do
    children = [B]
    supervise(children, strategy: :one_for_one)
  end
end

So as you can see, my GenServer A is trying to supervise another called B.

Problem

The problem here is that everything in this example is deprecated. I tried following the instructions and read the new Supervisor docs, specially start_child which I think will be the correct substitute for the deprecated supervise, but unfortunately I don't understand how I can apply this to my code.

Question

How can I update my code so it does not use deprecated functions?


Solution

  • There is a dedicated section in Supervisor docs providing the example.

    defmodule A.Server do
      use Supervisor
    
      alias B
    
      def start_link, do:
        Supervisor.start_link(__MODULE__, nil, name: __MODULE__)
    
      @impl Supervisor
      def init(_) do
        children = [
          {B, [:arg1, :arg2]} # or just `B` if `start_link/0`
        ]
    
        Supervisor.init(children, strategy: :one_for_one)
      end
    end