Building Finite State Machines With Actors: Switchable Behavior
12 minutes to readToday we’re going to learn about one of the really cool things actors can do: change their behavior at run-time!
This capability allows you to do all sorts of cool stuff, like build Finite State Machines (FSM) or change how your actors handle messages based on other messages they’ve received.
Today, we’re going to cover how to make a basic FSM using switchable behavior. We’ll go over advanced FSM approaches in a future post.
Let’s start with a real-world scenario in which you’d want the ability to change an actor’s behavior.
Real-world Scenario: Authentication
Imagine you’re building a simple chat system using Akka.NET actors, and here’s what your UserActor
looks like - this is the actor that is responsible for all communication to and from a specific human user.
public class UserActor : ReceiveActor { private readonly string _userId; private readonly string _chatRoomId; public UserActor(string userId, string chatRoomId) { _userId = userId; _chatRoomId = chatRoomId; Receive<IncomingMessage>(inc => inc.ChatRoomId == _chatRoomId, inc => { // print message for user }); Receive<OutgoingMessage>(inc => inc.ChatRoomId == _chatRoomId, inc => { // send message to chatroom }); } }
So we have basic chat working - yay! But… right now there’s nothing to guarantee that this user is who they say they are. This system needs some authentication.
How...