I am trying to implement an Akka actor which receives a message and then waits to receive another message without looping. The reason that I am trying to implement it this way is because I require the object received in the first case statement in the second case statement. Below is an example of what I mean.
def receive: Receive = {
case s @ start =>
receive {
case e @ end =>
println(f"Received ${s} and ${e}")
}
}
I am aware that this might not be the ideal pattern. However, I am still new to Akka and Scala and am not aware of any other way to implement this. All suggestions are welcome.
This is a good way to achieve this:
Create a second receive method that just waits for the second message. Use context.become
to set this method as the receive function when the first message arrives. The s
value can be a parameter of this method.
When the second message arrives, it is handled by the new receive method. Use context.become
to restore the original receive
method once the message is processed.
You can use the Stash
support to stash
any other messages that come when the second receive method is active. When an unexpected message arrives, stash
the message. When the correct message has been processed and the original receive handler has been restored, call unstashAll
to put them back on the queue. These messages will be re-sent to the actor in the original order to be processed by the main receive
method.
It might look like this:
def receive: Receive = {
case s @ start =>
context.become(endReceive(s))
// Other cases
}
def endReceive(s: ???): Receive = {
case e @ end =>
println(f"Received ${s} and ${e}")
context.become(receive)
unstashAll()
case _ =>
stash()
}