giraffe
giraffe

Reputation: 801

Receive multiple messages in an Erlang process

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?

Upvotes: 1

Views: 1368

Answers (1)

giraffe
giraffe

Reputation: 801

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.

Upvotes: 2

Related Questions