Day19 - Interpreting Machines - 2 :使用 interpret API

1. 写好 Machine Config 传入 createMachine API

https://ithelp.ithome.com.tw/upload/images/20210926/20130721htU67KKipL.png

const doorMachine = createMachine({
  // Machine identifier
  id: "door",

  // Initial state
  initial: "关着",

  // State definitions
  states: {
    关着: {
      on: {
        // 也可以用字串描述
        开门: "开了"
      }
    },
    开了: {
      on: {
        // 可用物件描述
        关门: { target: "关着" }
      }
    }
  }
});

2. 使用 interpret 建立 instance / service

使用 interpret API 来建立 service,并且 透过 onTransition 监听 转移,每当有转移时就可以执行一个 callback ,参数是 state ,我们这里先尝试用 console 每当转移时就印出 state。

// Interpret the machine, and add a listener for whenever a transition occurs.
const service = interpret(doorMachine).onTransition((state) => {
  console.log(`State is ${state.value}`);
});

3. 与 service 互动

3-1. 启动 service

// Start the service
service.start();

3-2. 操作 service,派发事件

console.warn("send Event 开门");
service.send("开门");  // 用 string 表示 event 
console.warn("send Event 关门");
service.send("关门");
console.warn("send Event 关门 again");
// 关着状态 + 关门事件,不转移状态
service.send({ type: "关门" });  // 也可以用 object 表示 event
console.warn("send Event 开门 again");
service.send({ type: "开门" });

https://ithelp.ithome.com.tw/upload/images/20211004/20130721UVjd999kOQ.png

3-3. 结束 service (当你不再需要使用这个状态机时)

// Stop the service when you are no longer using it.
service.stop();

假设此时我们在底下继续执行这个 instance

// Stop the service when you are no longer using it.
service.stop();
console.warn("send Event 开门 again");
service.send({ type: "开门" });

它不会继续运作,我们会看到 XState 在主控台用 warning 提示,此时可以再透过 start 方法,重启 service

// Restart the machine
service
  .start()
  .onTransition((state) =>
    console.error("重启了的 Machine State 是 ", state.value)
  );
  
service.send({ type: "关门" });

codesandbox Demo

小回顾

今天学习了 如何建立 state Machine 的 instance / service ,包含启动、派发事件、关闭、重启、监听转移事件等

之前提到下面的几个特色,除了第一点,其他也会在後续继续带大家一起认识

  • 需要持续追踪当前的 state ,并且保存它!(浪费这麽多变数储存似乎不妥?)
  • 需要执行 Side Effects (包含操控 I/O、Call API、写入档案、印出萤幕...)
  • 延迟处理 or 处理延迟的 转移 (Transition) 及 事件 (Event)
  • 跟外部的服务(Service)沟通

参考文献

https://xstate.js.org/docs/guides/interpretation.html#interpreting-machines


<<:  【Day19】SPI 状态机的实现

>>:  Day 19 民生公共物联网资料应用竞赛,产品设计讨论过程分享

Day 16 JavaScript boxing vs unboxing

boxing: 封装可以让原始型态的资料暂时转成物件,这样他才可以使用属性或方法。 遇到使用字面值(...

28. 团队成功的要素是什麽?

前言 这个演讲蛮general的,也适合任何leader来看看。如果你觉得team里面的人都不太爱...

[Day 8] Course 2_Ask Questions - 将利益相关者(Stakeholder)放在心上

《30天带你上完 Google Data Analytics Certificate 课程》系列将...

springboot连rabbitMQ的简介

开一个 docker-compose.yml 填入 version: "3.5"...

服务器运作简介

今天是第一天,我先简单的介绍一下网站服务器是如何运作的。还有如果在遭遇大量流量时,可能会有哪些状况。...