1
votes

I'm having trouble understanding how to receive multiple messages with an Erlang process. Here's what I tried in the shell:

1> GetMessage = spawn(fun() -> getMessage() end).
<0.252.0>
2> GetMessage ! msg.
Got a message
msg
3> GetMessage ! msg
msg

Code for getMessage/0:

getMessage() ->
  receive
    _ ->
      io:format("Got a message~n", [])
end.

How can I keep receiving messages?

1

1 Answers

2
votes

Ah, got it:

getMessage() ->
  receive
    _ ->
      io:format("Got a message~n", [])
      getMessage() % Add this line!
end.

You need to call the function again after receiving the message.