iT邦幫忙

2021 iThome 鐵人賽

DAY 19
0
Software Development

From State Machine to XState系列 第 19

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


上一篇
Day18 - Interpreting Machines - 1 :什麼是 Interpret ?
下一篇
Day20 - 在 XState 與 Side Effect 互動吧~ action API
系列文
From State Machine to XState31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言