Watching an actor

If we look back to the Chef actor's implementation, we'll be able to see that our system is now stuck. This happened because, if mixers fail, they are stopped by an external supervising force. However, the Chef actor is still waiting for this mixer's part to work. It turns out that we need a way to inform the Chef about terminated mixers.

Akka Typed offers a watching mechanism for this. To watch for mixers that were stopped, we'll add the following code to the Chef:

val mixers = for (i <- 1 to eggs) 
yield context.spawn(Mixer.controlledMix, s"Mixer_$i")
mixers.foreach(mixer => context.watchWith(mixer, BrokenMixer(mixer)))

Here, for each spawned Mixer, we're calling context.watchWith. The first parameter is an actor to watch and the second parameter is a message adapter. The need for the message adapter comes from the fact that the proper message type for the terminated actor would be akka.actor.typed.Terminated. We could use a watch, taking just a single actor reference, to subscribe to this message type—def watch[T](other: ActorRef[T]): Unit.

But, the fact is that our Chef can't handle this message type because it does not belong to its Command type. Therefore, we would need to define a separate actor type to watch for mixer terminations. Instead, we need to use the extended version of the watch method, which takes a message to be sent as a second parameter. The BrokenMixer message is defined and handled as follows:

case class BrokenMixer(mixer: ActorRef[Mixer.Mix]) extends Command

def mixing(...): Behavior[Command] = Behaviors.receivePartial {
...
case (context, BrokenMixer(m)) =>
context.log.warning("Broken mixer detected {}", m)
context.self ! Collect(Dough(0), m)
Behaviors.same
}

In this case, if we detect a terminated child actor, the Chef writes a log entry and sends itself a message to compensate for the lost part of the work. 

Now, we have the Dough ready and need a Cook to form cookies and a Baker to bake them in the Oven. The implementation of the Cook is trivial—it just converts Dough into a number of RawCookies and sends them back to the manager. Please refer to the code in the GitHub repository if you're interested in the implementation details.

..................Content has been hidden....................

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