blisscs
Comment on Mint's receive block
As an example for receiving messages return from Mint.HTTP.request/4, in the Mint manual from the official document at https://hexdocs.pm/mint/Mint.HTTP.html#content. it is written -
receive do
message ->
case Mint.HTTP.stream(conn, message) do
:unknown -> handle_normal_message(message)
{:ok, conn, responses} -> handle_responses(conn, responses)
end
end
From this sample code, you can see that the receive block pulls off whatever the first message that is in the process’s message queue, and then it checks again the Mint.HTTP.stream/2 to see that the first message is of the right message type that is sent back to this process by issue the HTTP action. If it is not of the wanted type, it discards that message and then it continues to find the message from the remaining messages in the Process Message block queue.
As Erlang processes can receive messages from any other processes, I think that we should use a more specific pattern to match the exact pattern that could be returned from using Mint library, just to preserve the non-Mint’s messages in the front of the process memory block queue.
–
Some editions to the original message above as pointed out by @jwarlander in the comment below -
the messages that got fetched out of the queue didn’t get discarded, they are been sent to handle_normal_message(message) to handle those messages.
So to rephrase, What I want to point out here is that these messages that could not be handled by this mint’s receive block, should not be fetched out at the time of this receive block is called. And we can use another strict pattern to match what we want instead of matching to anything in front of the queue.
Most Liked
jwarlander
Normally I think you would / should know what messages to expect, eg. those that relate to the purpose of your process. In this specific case, you could most often easily pattern-match any other messages you expect first, then pick it off and check if it’s a Mint message as the final case.
The problem with selective receive is that it can have a performance penalty if your mailbox has a lot of messages in it; also, you usually want a catch-all case somewhere in your main process loop to avoid message overflow.
For more in-depth info, see eg. https://www.erlang-solutions.com/blog/receiving-messages-in-elixir-or-a-few-things-you-need-to-know-in-order-to-avoid-performance-issues.html which is a good overview.







