Search code examples
elixirelixir-iex

Why my receive method is stopping my iex?


I wrote the following code on my iex terminal and after that it does not respond anymore, the terminal just stop, like it was expecting something else. What is actually happened?

receive do 
    {:hello, msg} -> msg          
    {:world, msg} -> "won't match" 
end

enter image description here


Solution

  • receive by default has no timeout so the process will be blocked until a message matching any of the pattern is received by the current process. If you're just playing around, you can set a timeout using after to make sure this doesn't happen:

    receive do
      {:hello, msg} -> msg
      ...
    after 5000 -> :timeout
    end
    

    If no message matching the pattern is received in 5000ms, the expression will now return :timeout.