scalarookie scalarookie - 1 month ago 9
Scala Question

How to only process messages from child actors?

I built an Akka FSM that spawns two child actors in its constructor and only receives messages from one of them.

val lhsRef: ActorRef = context.actorOf(Props(new PrimitiveNode(tpe)), "lhs")
val rhsRef: ActorRef = context.actorOf(Props(new PrimitiveNode(tpe)), "rhs")


When dealing with incoming events, I want to filter for those that come from
lhsNode
. I tried to achieve this the following way:

when(WaitFor1) {
case Event(event: SomeEventType, _) =>
// Control flow reaches this point but...
if (sender == lhsRef) {
// ...it never enters the if clause.


This does not work. In fact,
sender
and
lhsNode
are not equal, even though it's definitely
lhsNode
that sends messages to my FSM.

sender() Actor[akka://default/user/$a#670517729]
lhsNode Actor[akka://default/user/$a/$a/$b/lhs#-354253348]


What am I doing wrong?

Answer

Compare only the names of the sender and lhs. Check if message is really sent by the lhsNode.

sender.path.name == "lhs"

or

sender.path.name = lhsNode.path.name

Ensure that the sender is the lhs actor only. forward the message if any other actor is involved in between.

Something like below

when(WaitFor1) {
  case Event(event: SomeEventType, _) =>
    // ...
    if (sender.path.name == "lhs") {
      // ....

with Pattern match guard

when(WaitFor1) {
  case Event(event: SomeEventType, _) (if sender.path.name == "lhs") =>
Comments