Lots of Actors communicating with each other in ordered sequence

Hey there,

I am completely new to Akka but I am fascinated by what I have seen so far. However, I can’t get my head around an (as I assume) simple task:

Let’s assume 4 Actors (A, B, C, D).

Now A eventually emits a message to B.

Let’s further assume, that the message causes B to ask C and given the answer, it should ask something else to D and finally return the answer to A.

So the whole communication it would look something like this:

A: B ! SomeMessage
    // then:
    B: C ? SomeQuestion
    // then:
    C: B ! Answer(value)
    // then:
    B: D ? AnotherQuestion(value)
    // then:
    D: B ! AnotherAnswer(anotherValue)
    // finally:
    B: A ! FinalAnswer(anotherValue)

I tried to implement the above scenario in Scala, but it seems to end up in horrible code:

class B extends Actor {
  override def receive: Receive = {
    case SomeMessage => 
      (C ? SomeQuestion).map( response => {
        case Answer(value) => (D ? AnotherQuestion(value)).map( response2 => {
          case AnotherAnswer(anotherValue) => sender ! FinalAnswer(anotherValue)
        }) 
      })
  }
}

This can’t be the solution, right? How could this be solved in Akka?

Thanks, Simon

BTW: forgive me if my scala code might be ugly, but I am new to Scala too. Any suggestion of improvement is appreciated ;-)

One important thing is that you must not access sender() from Future operators or callbacks because those run in threads outside the actor. Instead capture the sender in a stable val first.

The ask code can be cleaned up by using for comprehensions, see https://doc.akka.io/docs/akka/current/futures.html#functional-futures