13.3. How to Communicate Between Actors
Problem
You’re building an actor-based application and want to send messages between actors.
Solution
Actors should be sent immutable messages with the !
method.
When an actor receives a message from another actor, it also
receives an implicit reference named sender
, and it can use that reference to send
a message back to the originating actor.
The general syntax to send a message to an actor is:
actorInstance
!
message
For example, if you have an actor instance named car
, you can send it a start
message like this:
car
!
"start"
In this case, the message is the String
literal start
. The car
actor should receive this message in a
match expression in its receive
method, and from there it can send a message back to whoever sent the
start
message. A simplified version
of a receive
method for car
might look like this:
def
receive
=
{
case
"start"
=>
val
result
=
tryToStart
()
sender
!
result
case
_
=>
// do nothing
}
As mentioned, the sender
instance is implicitly made available to your actor. If you just want to
send a message back to the code that sent you a message, that’s all you
have to do.
Discussion
To demonstrate a more complicated example of actors communicating, the following code shows how to send messages back and forth between Akka actors. It was inspired by the “Ping Pong” threading example in the book by James Gosling et al., The Java Programming Language (Addison-Wesley Professional):
import
akka.actor._
case
object
PingMessage
case
object
PongMessage ...
Get Scala Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.