liveBook · Manning

Receive expression

As explained in Elixir in Action, Third Edition

A receive expression removes and pattern-matches messages from the current process's mailbox, optionally waiting for a matching message or timing out.

A receive expression lets an isolated Elixir process cooperate with other processes by pulling messages from its mailbox, pattern-matching them, and running the matching branch. Because sending is asynchronous, the sender continues while the receiver decides when to handle the message. section 5.2.2

receive do
 pattern_1 -> do_something
 pattern_2 -> do_something_else
end

Use the branch structure as the basic receive template: each pattern selects handling code for one message shape. section 5.2.2

A practical receive expression can:

  • Match a general message or destructure a specific term such as {:message, id}. section 5.2.2
  • Wait indefinitely when no matching message is available, suspending the process without consuming CPU. section 5.2.2 section 5.3.1
  • Return the value produced by its selected branch, allowing received data to flow into ordinary expressions. section 5.2.2
  • Use an after clause to stop waiting and produce a timeout result when a message does not arrive. section 5.2.2 section 5.3.1

Collecting asynchronous query results

A caller can spawn workers, send each worker the caller PID, and wait for {:query_result, result} messages. Repeating a small get_result function gathers the results after the work runs concurrently. The arrival order can differ from submission order, so message-driven code should not assume completion order. section 5.2.2

Receive inside a server loop

A long-running server combines receive with tail recursion: it waits for a request, performs the work, sends a response to the caller, and calls loop() again. This creates an idle process that handles requests on demand. section 5.3.1

How Elixir in Action, Third Edition covers it

How deep it goes
Explains syntax, pattern matching, blocking, timeouts, return values, and server-loop use without detailing mailbox internals.
Examples
Demonstrates self-sent messages, tagged tuples, asynchronous queries, timeout handling, and a database server pool.
What it assumes
Assumes familiarity with Elixir expressions and pattern matching while teaching mailbox communication and process coordination through examples.
What you can do after
Build it from scratch as a message receiver, asynchronous result collector, or long-running server loop.
How it connects
Connects process identifiers, message passing, pattern matching, spawning, tail recursion, and server processes.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Elixir in Action, Third Edition. The section links point to the parts of the book it draws on.