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

Elixir Processes

livebook/elixir_processes.livemd

Elixir Processes

Simple Process

process_id = self()

spawn(fn -> send(process_id, {:hello, "Message sent and received"}) end)

receive do
  {:hello, message} -> IO.puts(message)
end

Process.info(self(), :messages)
Message sent and received
{:messages,
 [
   nonmatchingkey: "Message sent and received",
   nonmatchingkey: "Message sent and received",
   nonmatchingkey: "Message sent and received",
   nonmatchingkey: "Message sent and received",
   nonmatchingkey: "Message sent and received"
 ]}

Simple Process with Timer

process_id = self()

spawn(fn -> send(process_id, {:nonmatchingkey, "Message sent and received"}) end)

receive do
  {:hello, message} -> IO.puts(message)
  {:hello, _any} -> IO.puts("Key match found")
  {:nonmatchingkey, msg} -> IO.puts(msg)
after
  1_000 -> IO.puts("No matching key was found")
end
Message sent and received
:ok

Simple Simple Process

spawn(fn -> IO.puts("Hello world!") end)
|> Process.info(:memory)

Process.info(self(), :messages)
Hello world!
{:messages,
 [
   nonmatchingkey: "Message sent and received",
   nonmatchingkey: "Message sent and received",
   nonmatchingkey: "Message sent and received",
   nonmatchingkey: "Message sent and received",
   nonmatchingkey: "Message sent and received",
   nonmatchingkey: "Message sent and received"
 ]}

Process inside Module

defmodule Salutator do
  def run do
    receive do
      {:hi, name} -> IO.puts("Hi #{name}")
      {_, name} -> IO.puts("Hello #{name}")
    end

    # to enable sending & receiving multiple messages
    run()
  end
end