Request-Response with the ask pattern

165 views Asked by At

I am fairly new to Akka and went through this request-response example of the Akka documentation.

I understood this pattern works like the following:

  1. Dave asks Hal by sending a message of Hal's protocol.
  2. Hal answers by sending a message of its own protocol to Dave.
  3. Dave, who does not know Hal's protocol gets the response adapted and re-sent to itself.
  4. Dave receives the adapted response and continues with its payload.
context.ask(dave, Dave.Request) {
  case Failure(exception) => throw exception
  case Success(response) => AdaptedResponse(response.payload)
}

But what happens, if Dave needs response.payload diretly on the spot? Is this even possible?

1

There are 1 answers

0
Levi Ramsey On

In Akka Typed, it's not possible using context.ask, though I would question why you specifically need it.

As an alternative, when you have two actors which interact, you can define a joint-protocol between them:

object Hal {
  sealed trait Command

  sealed trait CommandFromDave extends Command {
    def replyTo: ActorRef[Dave.ResponseFromHal]
  }

  case class OpenThePodBayDoorsPlease(override val replyTo: ActorRef[Dave.ResponseFromHal]) extends CommandFromDave
}

object Dave {
  sealed trait Command

  sealed trait ResponseFromHal extends Command

  case class MessageFromHal(msg: String) extends ResponseFromHal
}

Then Dave can just

hal ! Hal.CommandFromDave(context.self)

and get the response directly from Hal (and you can schedule a message to yourself to account for the timeout).

Note that this really entangles two actors together. It's suitable for cases like where a parent actor defers a long-running task to a child actor, but it's a really questionable approach in most/all other scenarios.