So far we have discussed about actors and actor supervision that leads us to keep the system alive. In this post lets explore another Actor feature that provide us to be a stateful actor. It basically let us to change an Actor’s running behavioural state while message is processed. So we can change the way it reacts to future messages in any way we want. Hence, this will help us to change the behaviour of our actors based on its internal state.
Now lets take our Family ActorSystem example and try to understand. Son (Roy) is addicted to junk food. When Mother (Mary) realize that her son ate junk food she always goes crazy and shouts at him. So we can see Mother’s behaviour is changing according to her son’s state (Figure 1).
Like in Figure 1 we will come across so many situation in our application domain. Therefore, to handle these situation the primary way that Akka let us to modify the actor behaviour is by simply using the ActorContext’s become() and unbecome() methods.
To handle the two behaviours in Mother Actor the two following Receive methods are implemented.
And also the Son Actor’s Receive methods will be as follow,
By executing the sample application, we can see how the behaviours are changed in the Actor model.
Conclusion
We can see become() and unbecome() methods come very handy. By default receive method is used to handle all incoming messages. However at any time if we need to change the behaviour we can use the become() method, which accepts as arguments with a return type of receive signature. Once we change the receive method all the messages that are sent to the Actor model will be handled by the new method. unbecome() method is contrast to the become() method. By executing the unbecome method we will be able to restore to the original receive method.