Skip to content

Instantly share code, notes, and snippets.

@adolfont
Created October 19, 2023 19:38
Show Gist options
  • Save adolfont/a928aff184191f11a24fa9cb4008b79d to your computer and use it in GitHub Desktop.
Save adolfont/a928aff184191f11a24fa9cb4008b79d to your computer and use it in GitHub Desktop.

Handling state between multiple processes with Elixir

Spawning a process

Code from the Handling state between multiple processes with elixir, a blog post by Cherry Ramatis.

pid = spawn(fn -> IO.puts("teste") end)
pid
Process.alive?(pid)

Spawning another process

pid =
  spawn(fn ->
    :timer.sleep(10000)
    IO.puts("teste")
  end)
Process.alive?(pid)

Wait a few seconds, until "test" appears above.

Process.alive?(pid)

Listener module

defmodule Listener do
  def call do
    receive do
      {:hello, msg} -> IO.puts("Received: #{msg}")
    end
  end
end
pid = spawn(&Listener.call/0)
send(pid, {:hello, "Hello World"})

Tasks

task =
  Task.async(fn ->
    IO.puts("Task is running")
    42
  end)
IO.puts("a code")
answer_to_everything = Task.await(task)
answer_to_everything

Listener2

defmodule Listener2 do
  def call do
    receive do
      {:print, msg} -> IO.puts("Received message: #{msg}")
    end
  end
end
{:ok, pid} = Task.start(&Listener2.call/0)
send(pid, {:print, "Eat more fruits"})

Designing state with the Agent wrapper

{:ok, agent} = Agent.start_link(fn -> [] end)
agent
Agent.update(agent, fn list -> ["elixir" | list] end)
Agent.get(agent, fn list -> list end)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment