createMachine API
const doorMachine = createMachine({
  // Machine identifier
  id: "door",
  // Initial state
  initial: "關著",
  // State definitions
  states: {
    關著: {
      on: {
        // 也可以用字串描述
        開門: "開了"
      }
    },
    開了: {
      on: {
        // 可用物件描述
        關門: { target: "關著" }
      }
    }
  }
});
使用 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-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: "開門" });

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: "關門" });
今天學習了 如何建立 state Machine 的 instance / service ,包含啟動、派發事件、關閉、重啟、監聽轉移事件等
之前提到下面的幾個特色,除了第一點,其他也會在後續繼續帶大家一起認識
https://xstate.js.org/docs/guides/interpretation.html#interpreting-machines