Press "Enter" to skip to content

Using State Machine in Xamarin Forms (Part 1)

A state machine is a well-known paradigm for developing programs, it provides a modeling style with which you can model your workflow in an event-driven manner. 

By using state machine, it is easier to handle/define multiple states in one place, which makes your code easier to maintain and read. 

There is a great .NET library called Stateless, which allow you to use this paradigm to handle states in .NET Apps. In this article I’m going to show you how to use it in a Xamarin Forms App, by handling the states of a video player.

Let’s start with the basics 

First, you need to define the different states that you want to handle. For this sample, since it is a video player the states are:

  • Idle : Initial State
  • Playing : Video Playing
  • Paused : Video Paused
  • Stopped : Video Stopped

Define and Implement State Machine

1. Install the Stateless package in your XF Project.

2. Create an Enum to represent the different states

3. Create an Enum to represent the Trigger actions that can change the state.

4. Create your State Machine in your ViewModel

It’s created by specifying two generic types the state and the trigger. Also, you specify the initial state by passing it as a parameter.

5. Configure each state

For each configuration we are going to set the following:

  • Configure -> The state been configured
  • OnActivate -> Action you want to happen when calling the Activate method.
  • OnEntry -> Action you want to happen when entering that state.
  • Permit -> Defines what triggers are allowed for the current state and which new states can be set.

By configuring each state you define what’s allowed on a particular state and what can trigger a state change.

6. Create a Command to handle when Play, Pause or Stop buttons are tapped.

Create a VideoActionCommand, that will be used to call the actions we want to be executed by the media player.

7. Call the Activate() method

Once you have defined all state rules call the Active() method, it will call the OnActivate() method for the states that have defined it.

Create the user interface

1. Install the Xamarin Community Toolkit package

2. Extend the MediaElement control to add a Command property that will handle video actions

When executing this command it will execute video player actions.

3. Create the XAML

Result

That’s it for now, stay tuned for the next part where we’ll talk more about this topic. Check the full source code here.

Happy Stateless!