Sunday 26 May 2019

Introduction to State Machine for IOS App

Demo:
https://github.com/Sylvia-YiyinShen/StateMachineDemo


Why State Machine pattern? What we want to achieve? What are the benefits introducing State Machine?

 1. We want to define rules of transition, final state if needed to end the transitions as well. Un-allowed transitions can be stopped at compiling stage.
 2. Since there might be more than one state machines within the whole app, we want to control the existence of state machines(lifecycle of modules).E.g we have SignIn and MainWorkflow state machines, MainWorkflow should not exist until login state has been entered.


 Prototyping process

 1. For each module, we want to define several states, enum is a good choice.
 2. Each state machine is responsible for a single set of states enum, however we hope the state machine class can be reused, so we have to make enums conform to one struct/class.
 3. For each state, we want to maintain the allowed transitions which has to be stored property. Since enum does not support store properties, we need a wrapper struct/class of state enum. So we need the help of Generics.

 protocol StateIdentifier
 class State<T> where T: StateIdentifier
 class StateMachine<T> where T: StateIdentifier


 In this example, we will have two state sets and accordingly two state machines

 enum SignInState: StateIdentifier
 enum MainWorkflowState: StateIdentifier

 For simplicity, state machines initialisation and configuration are handled in the view controller, ideally we can put in an appCoordinator-like role.

 Check configureStateMachine() in ViewController.swift. The configuration requires
 1. Initialize the states along with the transition rules
 2. Configure state.didEnter .willExit
 3. Initialize a state machine with the above states injected

 In this simple demo, I am just using a label to indicate where we are at.
 Play around the buttons to see how the main workflow module is blocked by sign in/out state.

By introducing state machine, regardless of the messy buggy or wrong routing logic, we will never break the transition rules we've set up.

No comments:

Post a Comment