zoukankan      html  css  js  c++  java
  • [XState] Use an Interpreter to Instantiate a Machine

    While it's powerful enough to have Machine.transition, it can get tedious constantly passing it a state and an event. It would be nice if we had a function that could take a machine, instantiate it, maintain the state of the machine, and give us the ability to send events to it.

    This is where an interpreter comes in handy.

    And interpreter takes the abstract machine and brings it to life. XState provides us a function, interpret, to do this. interpret returns to us a service and we can use that service to send events, subscribe to changes, and add callbacks to events such as onTransition

    const { Machine, interpret } = 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
    });
    
    const service = interpret(lightBulb)
      .onTransition(state => {
        // Side effect
        if (state.value === "broken") {
          console.log("Light bulb is borken");
          service.stop();
        }
    
        // check the state is changed or not
        if (state.changed) {
          console.log("changed to: ", state.value);
        }
      })
      .start(); // unlit when start
    
    service.send("TOGGLE"); // lit after toggle
    
    service.send("BROKEN"); // borken
  • 相关阅读:
    OCP-1Z0-051-V9.02-55题
    OCP-1Z0-051-V9.02-60题
    OCP-1Z0-053-V12.02-59题
    OCP-1Z0-053-V12.02-184题
    OCP-1Z0-053-V12.02-595题
    OCP-1Z0-053-V12.02-584题
    OCP-1Z0-053-V12.02-234题
    OCP-1Z0-053-V12.02-548题
    OCP-1Z0-053-V12.02-549题
    OCP-1Z0-053-V12.02-551题
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12210587.html
Copyright © 2011-2022 走看看