Process Mailbox
Mix.install([
{:jason, "~> 1.4"},
{:kino, "~> 0.9", override: true},
{:youtube, github: "brooklinjazz/youtube"},
{:hidden_cell, github: "brooklinjazz/hidden_cell"}
])
Navigation
Home Report An Issue Process DrillsGeneric ServerProcess Mailbox
You’re going to create a Mailbox using a process which loops and receives messages.
mailbox_process = spawn(fn -> Mailbox.loop() end)
You should be able to send the Mailbox a message to add a virtual letter to the mailbox.
Print the current list of letters during every loop to prove your spawned process is storing every message in its state.
send(mailbox_process, {:mail, "You've Got Mail!"})
# ["You've Got Mail!"]
send(mailbox_process, {:mail, "You've Got Mail..Again!"})
# ["You've Got Mail..Again!", "You've Got Mail!"]
We won’t typically work directly with processes like this. Instead we’ll rely on abstractions such as GenServer which we will learn about in a future lesson.
Example Solution
defmodule Mailbox do
def loop(state \\ []) do
IO.inspect(state)
receive do
{:mail, letter} -> loop([letter | state])
end
end
end
Implement the Mailbox module below.
defmodule Mailbox do
@moduledoc """
Documentation for `Mailbox`
"""
@doc """
Recursively loop and receive messages.
## Examples
iex> counter_process = spawn(fn -> Mailbox.loop() end)
iex> send(counter_process, {:mail, "Hello!"})
"""
def loop(state \\ []) do
end
end
Commit Your Progress
DockYard Academy now recommends you use the latest Release rather than forking or cloning our repository.
Run git status to ensure there are no undesirable changes.
Then run the following in your command line from the curriculum folder to commit your progress.
$ git add .
$ git commit -m "finish Process Mailbox exercise"
$ git push
We’re proud to offer our open-source curriculum free of charge for anyone to learn from at their own pace.
We also offer a paid course where you can learn from an instructor alongside a cohort of your peers. We will accept applications for the June-August 2023 cohort soon.