2
votes

I am using an actor inside a request with the "ask" pattern:

val route =
    pathPrefix("myapp") {
      path("search") {
        get {
          (mainActorRef ? DoSomething("foo")).mapTo[ReturningType].map { result =>
  complete(HttpEntity(ContentTypes.`application/json`, result ))
         }
        }
      }
    }

The problem is that the main actor communicates with other actors and gets an answer back from one of those actors like this:

class MainActor extends Actor {

  override def receive: Receive = {

    case d:DoSomething =>
      anotherActor ! DoThis(d)

    // received from anotherActor as reply to DoThis
    case r:DoThisResponse =>
      // how do I send the response back to my “route”?
      pipe (Future{r}) to ???
  }

}

How can I send this answer back to Akka-Http as response?

Using "sender()" in the main actor doesn't work as it won't be the right reference. Should I pass in the DoSomething some reference to use with "tell" (!) inside the main actor? How do I pass this reference?

1

1 Answers

2
votes

Use forward instead of tell in the the MainActor when sending to anotherActor. That way anotherActor will not "see" MainActor as the sender .

So, basically, you send new messages in the intermediate steps with forward, but the actor in the line can simply respond to sender, since it does not see the intermediate actors.

Edit: a complete MainActor

class MainActor extends Actor {

override def receive: Receive = {

   //delegating some more work to another container
   case d:DoSomething =>
     anotherActor forward DoThis(d)

   // sending a response back to "route"
   case r:DoThisResponse =>
     sender ! Response

    }
}