Press "Enter" to skip to content

Using State Machine in Xamarin Forms (Part 3)

In the second part of this series about State Machine, we covered how to do internal transitions by showing an example that added Rewind/Forward capabilities to the MediaPlayer. In this part, we will cover how to pass parameters to Triggers.

Understanding how to pass parameters

Stateless library allows you to pass parameters to Triggers, this is really handy when you need to work with external parameters. For example, in our video player, if we want to change the seconds used for forwarding/rewinding, we need a way to pass those parameters to the triggers to respond accordingly.

To achieve this we can use parameters the following syntaxis:

var myTriggerParam = stateMachine.SetTriggerParameters<string>(Trigger.MyTrigger);

stateMachine.Configure(State.MyState)
    .OnEntryFrom(myTriggerParam, param => //Handle the param here);

Let’s code it

First, we are going to create two TriggersParameters (For Forward and Rewind). Then will associate them to the triggers VideoTrigger.Forward and VideoTrigger.Rewind.

Second, we will replace the InternalTransition that we were using for Forward/Rewind with OnEntryFrom instead. Also, add a PermitReentryIf for those triggers since it will allow reentering to the same state.

We will create two commands for Forward and Rewind, which will get the parameter set by the user and then fire the trigger with the parameter.

Finally, we add the buttons for Rewind and Forward to the UI. Also, a stepper to change the seconds dynamically.


Result

That’s all for now!

Check the full source code here.

Happy Stateless!