Search code examples
elixirerlang-otp

What is the correct way to start `:pg`'s default scope in an Elixir 1.12 application?


The :pg2 module was removed in OTP 24. It's replacement is :pg. According to the documentation:

Default scope pg is started automatically when kernel(6) is configured to do so.

From a mix-based Elixir 1.12 application, what is the right way to configure the kernel to start the default :pg scope automatically? So far, I've been doing this but it seems really hack-y makes writing library code that doesn't have a start/2 function impossible:

defmodule MyApp do
  use Application

  def start(_type, _args) do

    # Ew, gross:
    {:ok, _pid} = :pg.start_link()

    children() |> Supervisor.start_link([strategy: :one_for_one, name: __MODULE__])
  end

  def children, do: []
end

Solution

  • You can write your own child_spec for that module:

    defmodule MyApp do
      use Application
    
      def start(_type, _args) do
        Supervisor.start_link(children(), strategy: :one_for_one, name: __MODULE__)
      end
    
      defp children, do: [pg_spec()]
    
      defp pg_spec do
        %{
          id: :pg,
          start: {:pg, :start_link, []}
        }
      end
    end