ActorFlow.ask
Use the “Ask Pattern” to send each stream element as an ask
to the target actor (of the new actors API), and expect a reply that will be emitted downstream.
Dependency
The Akka dependencies are available from Akka’s library repository. To access them there, you need to configure the URL for this repository.
This operator is included in:
- sbt
val AkkaVersion = "2.10.2" libraryDependencies += "com.typesafe.akka" %% "akka-stream-typed" % AkkaVersion
- Maven
- Gradle
Signature
Description
Use the Ask pattern to send a request-reply message to the target ref
actor. If any of the asks times out it will fail the stream with an AskTimeoutException
.
The ask
operator requires
- the actor
ref
, - a
makeMessage
function to create the message sent to the actor from the incoming element, and the actor ref accepting the actor’s reply message - a timeout.
See also:
- Flow.ask for the classic actors variant
Examples
The ActorFlow.ask
sends a message to the actor. The actor expects Asking
messages which contain the actor ref for replies of type Reply
. When the actor for replies receives a reply, the ActorFlow.ask
stream stage emits the reply and the map
extracts the message String
.
- Scala
-
source
import akka.stream.scaladsl.{ Flow, Sink, Source } import akka.stream.typed.scaladsl.ActorFlow import akka.actor.typed.ActorRef import akka.actor.typed.scaladsl.Behaviors import akka.util.Timeout final case class Asking(s: String, replyTo: ActorRef[Reply]) final case class Reply(msg: String) final case class AskingWithStatus(s: String, replyTo: ActorRef[StatusReply[String]]) val ref = spawn(Behaviors.receiveMessage[Asking] { asking => asking.replyTo ! Reply(asking.s + "!!!") Behaviors.same }) implicit val timeout: Timeout = 1.second val askFlow: Flow[String, Reply, NotUsed] = ActorFlow.ask(ref)(Asking.apply) // explicit creation of the sent message val askFlowExplicit: Flow[String, Reply, NotUsed] = ActorFlow.ask(ref)(makeMessage = (el, replyTo: ActorRef[Reply]) => Asking(el, replyTo)) val in: Future[immutable.Seq[String]] = Source(1 to 50).map(_.toString).via(askFlow).map(_.msg).runWith(Sink.seq)
- Java
Reactive Streams semantics
emits when the futures (in submission order) created by the ask pattern internally are completed
backpressures when the number of futures reaches the configured parallelism and the downstream backpressures
completes when upstream completes and all futures have been completed and all elements have been emitted
fails when the passed-in actor terminates, or when any of the ask
s exceed a timeout
cancels when downstream cancels