I am trying to figure out, how the ask pattern works. In the documentation, it says:
Perform a single request-response message interaction with another actor, and transform the messages back to the protocol of this actor.
The interaction has a timeout (to avoid a resource leak). If the timeout hits without any response it will be passed as a Failure(java.util.concurrent.TimeoutException) to the mapResponse function (this is the only "normal" way a Failure is passed to the function).
For other messaging patterns with other actors, see ActorContext#messageAdapter.
This method is thread-safe and can be called from other threads than the ordinary actor message processing thread, such as scala.concurrent.Future callbacks.
Could someone please provide an example to get a better understanding of ask pattern.
'Ask pattern' is used in the code outside of actors to communicate with actors. Akka will create an actor for you behind the scenes, send a message and wait for reply within timeout. None of this will block your thread because a Future
result will be returned immediately which is expected to contain response later on. This is needed because actors can only communicate by sending messages and if you are not within an actor you can't receive a message. It's recommended to use 'tell' !
instead of 'ask' ?
because it's more efficient but sometimes there is no choice so you have to bridge two worlds together with 'ask'.
Look for examples on internet or try to call actors from main
method to get a feel of it.
When you need interact with another actor and also depend on its response you might use the tell method to send a message and wait for a new response message (fire-and-forget).
Due to the fact that Akka does not have guaranteed delivery, you might wait infinitely if the receiving actor is down.
Ask returns a Future[Response] that is either completed with a successful response or failed with a TimeoutException if there was no response within the specified timeout.
Please see the the example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With