Stop supervisor when no children are running anymore

Hi,

I’m using a Supervisor (one_for_one) supervising 2 GenServer (restart: :transient).

Is-there a way to stop automatically the Supervisor when the 2 children are stopped with {:stop, :normal} tuple?

Currently my 2 GenServers are stopped but my Supervisor keeps on running, doing nothing :slight_smile:

Help appreciated :wink:

One simple approach to get this done will be handling the exit of yours GenServer using
terminate, and running from there a new process in charge of stopping your supervisor if there is no more running childs.

At your GenServer you need to define this:

  def terminate(_reason, state) do
     Task.start(TransientSupervisor, :stop_transient_supervisor, [])
    {:ok, state}
  end

At the supervisor you need:

 def stop_transient_supervisor() do
    case Supervisor.count_children(TransientSupervisor) do
      %{active: 0} ->
        Supervisor.stop(TransientSupervisor, :normal)
      _ ->
        :ok
    end
  end

I have built a little POC at this repo.
Hope it helps :slight_smile: