Skip to content

Instantly share code, notes, and snippets.

@zachallaun
Created August 17, 2022 00:08
Show Gist options
  • Save zachallaun/aa2ce2a24660cb23341dfeeb23c51964 to your computer and use it in GitHub Desktop.
Save zachallaun/aa2ce2a24660cb23341dfeeb23c51964 to your computer and use it in GitHub Desktop.

Kino.Process - Non-started Processes

Mix.install([
  # {:kino, "~> 0.6.2", override: true}
  {:kino, path: "./", override: true}
])
:ok

Setup

start* functions can return :ignore, in which case the supervisor that tried to start it will cache the child spec and store its pid as :undefined. This allows you to Supervisor.restart_child/2 later using the child id.

Kino.Process currently assumes that all processes referenced in a supervisor have a live pid, causing things to go boom when pid is :undefined.

defmodule Example do
  use GenServer

  def start_link(opts) do
    {ignore, opts} = Keyword.pop(opts, :ignore, false)
    if ignore, do: :ignore, else: GenServer.start_link(__MODULE__, :ok, opts)
  end

  @impl true
  def init(:ok) do
    {:ok, nil}
  end
end
{:module, Example, <<70, 79, 82, 49, 0, 0, 20, ...>>, {:init, 1}}
defmodule ExampleSupervisor do
  use Supervisor

  def start_link(opts) do
    {ignore, opts} = Keyword.pop(opts, :ignore, false)

    if ignore, do: :ignore, else: Supervisor.start_link(__MODULE__, opts, opts)
  end

  @impl true
  def init(name: name) do
    children = [
      spec_for({Example, []}, Example1, name),
      spec_for({Example, ignore: true}, Example2, name),
      spec_for({Example, ignore: true}, Example3, name)
    ]

    Supervisor.init(children, strategy: :one_for_one)
  end

  defp spec_for({module, opts}, id, sup_name) do
    name = Module.concat(sup_name, id)
    opts = Keyword.put(opts, :name, name)

    Supervisor.child_spec({module, opts}, id: name)
  end
end
{:module, ExampleSupervisor, <<70, 79, 82, 49, 0, 0, 12, ...>>, {:spec_for, 3}}
children = [
  Supervisor.child_spec({ExampleSupervisor, name: Sup1}, id: Sup1),
  Supervisor.child_spec({ExampleSupervisor, name: Sup2}, id: Sup2),
  Supervisor.child_spec({ExampleSupervisor, ignore: true}, id: Sup3)
]

Supervisor.start_link(children, strategy: :one_for_one, name: Sup)
{:ok, #PID<0.245.0>}
Kino.Process.sup_tree(Sup)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment