# Lots of Actors communicating with each other in ordered sequence

**URL:** <https://discuss.akka.io/t/lots-of-actors-communicating-with-each-other-in-ordered-sequence/2851>\
**Category:** Akka Libraries\
**Created:** [December 1, 2018, 1:08pm UTC](https://discuss.akka.io/t/lots-of-actors-communicating-with-each-other-in-ordered-sequence/2851 "2018-12-01T13:08:29Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![simon-gunacker](https://avatars.discourse-cdn.com/v4/letter/s/7ba0ec/32.png) [@simon-gunacker](https://discuss.akka.io/u/simon-gunacker)\
**Post date:** [December 1, 2018, 1:08pm UTC](https://discuss.akka.io/t/lots-of-actors-communicating-with-each-other-in-ordered-sequence/2851/1 "2018-12-01T13:08:29Z")

</div>

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:

```auto
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:

```auto
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 ;-)

---

<div class="post-metadata">

**Author:** ![patriknw](https://sea2.discourse-cdn.com/flex020/user_avatar/discuss.akka.io/patriknw/32/89_2.png) [@patriknw](https://discuss.akka.io/u/patriknw)\
**Post date:** [December 5, 2018, 7:18pm UTC](https://discuss.akka.io/t/lots-of-actors-communicating-with-each-other-in-ordered-sequence/2851/2 "2018-12-05T19:18:41Z")

</div>

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](https://doc.akka.io/docs/akka/current/futures.html#functional-futures)
