Changing an actor's behavior using context

In the last line of code, the actor changes its behavior by using the context.become construct.

become and unbecome is an Akka way of changing the behavior of the actor in response to a message. become takes a Receive argument (which is a type alias for PartialFunction[Any, Unit], which is also just a normal sign of the receive method) which becomes a new actor's behavior starting from the next message (this change in behavior is not preserved across actor restarts). The discardOld parameter controls whether this new behavior should replace an old one or whether it should just push it down to the stack of behaviors that actors maintain internally. We'll see how this stack works in a minute.

Let's go over the waitingForResults method, which became a new behavior of the actor a moment ago. The first line puts any Groceries messages on hold because we are already waiting for jobs to be finished. This is done by using the stash() method of the Stash trait, which puts the current message into an internal stash of the actor: 

case g: Groceries => stash()

The Chef actor watches over the Mixer actors it has created. In this case, if a child actor dies, the watching actor will receive a Terminated message with an actor reference of the victim:

case Terminated(child) =>

The actor checks whether all of the children are terminated by using context.children, and if this is the case, it prepends all of the stashed messages to the message box by using unstashAll() and returns to its previous behavior by using context.unbecome().

Unbalanced context.become() and context.unbecome() operations might introduce the source of a memory leak in long-running applications.
Now that our Chef is ready, let's move on and implement a Manager
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.50.156