zoukankan      html  css  js  c++  java
  • [XState] Replace Enumerated States with a State Machine

    numerating the possible states of a function is a sound way to write a function, but it is imperative and could benefit from abstraction. We can do this with a state machine.

    A state machine formalizes how we enumerate states and transitions. For the sake of clarity and to emphasize the core concepts, I will be overly verbose with my code in this lesson.

    In this lesson, we'll replace the state enum with individual state objects. We'll also replace our events toggle() and break() with events TOGGLE and BREAK. I'll also demonstrate the usefulness of the Machine's initialState getter and the transition method. Lastly, I'll show what happens when we pass erroneous states or events into our machine.

    // enumeratds states
    const STATE = {
      LIT: "lit",
      UNLIT: "unlit",
      BROKEN: "broken"
    };
    
    function lightBulb() {
      let state = STATE.UNLIT;
    
      return {
        state() {
          return state;
        },
        toggle() {
          switch (state) {
            case STATE.LIT:
              state = STATE.UNLIT;
              break;
            case STATE.UNLIT:
              state = STATE.LIT;
              this.break;
          }
        },
        break() {
          state = STATE.BROKEN;
        }
      };
    }
    
    const bulb = lightBulb();
    const log = () => {
      console.log(bulb.state());
    };
    
    bulb.toggle();
    bulb.break();
    log(); // broken

    Using xstate:

    const { Machine } = require("xstate");
    
    const lit = {
      // 'on' keyword present events
      on: {
        TOGGLE: "unlit",
        BROKEN: "broken"
      }
    };
    const unlit = {
      on: {
        TOGGLE: "lit",
        BROKEN: "broken"
      }
    };
    const broken = {
      // you can leave it empty, the same as final state
      //type: "final"
    };
    
    const states = { lit, unlit, broken };
    
    const lightBulb = Machine({
      id: "lightBulb",
      initial: "unlit",
      strict: true,
      states
    });
    
    console.log(lightBulb.transition("broken", "TOGGLE").value); // broken
    console.log(lightBulb.transition("lit", "TOGGLE").value); // unlit
    console.log(lightBulb.transition("unlit", "TOGGLE").value); // lit
  • 相关阅读:
    Android 适配知识点
    Android Studio各种快捷功能及好用的插件
    81.Android之沉浸式状态栏攻略
    8.Android 系统状态栏沉浸式/透明化解决方案
    为开发者准备的 Android 函数库(2016 年版)
    GitHub 上 57 款最流行的开源深度学习项目
    7.Android开源项目WheelView的时间和地址联动选择对话框
    6.初探Asynctask
    5.Android消息推送机制简单例子
    让你Android开发更简单
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12209701.html
Copyright © 2011-2022 走看看