OTP applications

What an app is

An OTP application is a packaged component with its own supervision tree and configuration. Libraries ship code only, while applications also boot processes when the system starts. Thinking in applications turns a project into a set of clean boxes with clear borders.

IO.inspect(Application.get_env(:my_app, :greeting))

nil

Application callback

The Application module behaviour defines one start function that boots the supervision tree. It receives the start type and arguments, then returns whatever Supervisor.start_link returns. The runtime calls it automatically when the application boots, so no manual wiring is needed.

defmodule MyApp.Application do use Application def start(_type, _args) do children = [{Counter, 0}] Supervisor.start_link(children, strategy: :one_for_one) end end

Mix project with --sup

The mix new command with the sup flag generates a project whose application module already exists. Open lib/my_app/application.ex to find the callback from the previous section wired and ready. Rename the children list to match the servers the project truly needs.

mix new my_app --sup

Start it

The mix project file points at the callback module, so booting the project boots the tree. The run command with the no-halt flag starts everything and keeps the virtual machine alive. Stopping the command tears the tree down in reverse order.

def application do [mod: {MyApp.Application, []}] end

mix run --no-halt

Next: Mix projects

Article author: Arthur Isaev

Banner image