Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

Elixir Processes and GenServers - Part 1

genservers_1.livemd

Elixir Processes and GenServers - Part 1

0. Launch

Run in Livebook

1. Basic Processes: spawn()

Take a simple operation:

1 + 1 |> IO.puts()

Let’s run it in a different process.

spawn/1 creates a process and runs code in a provided function.

spawn(fn -> 1 + 1 |> IO.puts() end)

spawn/3 lets you specify module, function, and args.

defmodule Spawnable do
  def add(a, b) do
    a + b
    |> IO.puts()
  end
end

spawn(Spawnable, :add, [7, 8])

2. Message Passing

A spawned process can listen for messages.

defmodule BilingualGreeter do
  def listen_loop do
    receive do
      # print the greeting
      {:bonjour_hi, name} -> IO.puts("Bonjour hi, #{name}")

      # exit with reason
      {:goodbye} -> exit(:au_revoir)
    end
    
    listen_loop()
  end
end

Spawn the process:

greeter_pid = spawn(BilingualGreeter, :listen_loop, [])

Send a message:

send(greeter_pid, {:bonjour_hi, "Elixir Montréal"})

End the listen loop:

send(greeter_pid, {:goodbye})

Notice that we don’t see the exit reason.

3. Linking Processes

Let’s try again with a linked process:

greeter_pid = spawn_link(BilingualGreeter, :listen_loop, [])
send(greeter_pid, {:bonjour_hi, "Elixir Montréal"})
send(greeter_pid, {:goodbye})

Next