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
