zoukankan      html  css  js  c++  java
  • [XState] Use Activities in XState to Run Ongoing Side Effects

    Activities are continuous, ongoing side effects that are triggered by entering a particular state, and only stop when that state is exited. In the example in this lesson, we have an alarm clock machine that does the activity of beeping for the duration of the alarming state.

    Activities are a function that receives context and the event object (just like actions). They fire off the ongoing side effect in the body of the function, and optionally return a function that performs any cleanup necessary for the activity.

    const { Machine, interpret } = require("xstate");
    
    const alarmMachine = Machine(
      {
        id: "alramMachine",
        initial: "idle",
        states: {
          idle: {
            on: {
              BEEP: "beep"
            }
          },
          beep: {
            on: {
              IDLE: "idle"
            },
            activities: ["keepBeeping"]
          }
        }
      },
      {
        activities: {
          keepBeeping: (context, event) => {
            const beep = () => {
              console.log("beepping....");
            };
    
            beep();
            const handler = setInterval(beep, 1000);
            return () => clearInterval(handler);
          }
        }
      }
    );
    
    const service = interpret(alarmMachine)
      .onTransition(s => {
        console.log(s.value);
      })
      .start();
    
    service.send("BEEP");
    setTimeout(() => {
      service.send("IDLE");
    }, 5000);
  • 相关阅读:
    11月1号笔试题总结
    10月30笔试题总结
    web前端常用单词
    9月13日·碎碎念
    python 匿名函数
    python 二分法查找
    python 递归
    python内置函数
    python 列表生成式
    python 生成器
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12215853.html
Copyright © 2011-2022 走看看