How can I broadcast a message to all actors that are watching a particular actor?
For context, suppose I have a AuctionActor
(which is potentially a remote actor) that is being watched by a large number of AuctionParticipantActor
types. I would like the AuctionActor
to broadcast various messages to AuctionParicipantActor
types.
One possibility would be for the AuctionActor
to keep a collection of all participant ActorRef
instances and then loop over this collection when ever a message needs to be sent to all participants. This seems inefficient and I am hoping for a better solution...
If you don't want to go with PubSub as mentioned by Diego Martinoia, I would suggest using Routers
with BroadcastingLogic
. This goes in the direction you mentioned with the collection of ActorRefs, but uses Akka functionality to achieve it being more efficient than just iterating over a collection in your AuctionActor
.
From Akka Docs
Routers are designed to be extremely efficient at receiving messages and passing them quickly on to routees.
A normal actor can be used for routing messages, but an actor’s single-threaded processing can become a bottleneck. Routers can achieve much higher throughput with an optimization to the usual message-processing pipeline that allows concurrent routing.
In your case it could look like this:
class AuctionActor extends Actor {
var router = Router(BroadcastRoutingLogic(), Vector[ActorRefRoutee]())
def receive = {
case AddParticipant(ref) =>
router = router.addRoutee(ref)
case RemoveParticipant(ref) =>
router = router.removeRoutee(ref)
case update: ImportantUpdate =>
router.route(update, self)
}
}