[XState] Use Activities in XState to Run Ongoing Side Effects

Posted answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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);

 

以上是关于[XState] Use Activities in XState to Run Ongoing Side Effects的主要内容,如果未能解决你的问题,请参考以下文章

Server-side activities have been updated. You need to restart SharePoint Designer to use the updated

XState:在没有中间状态的情况下链接多个 Promise

XState 不会停留在空闲状态

[XState] Track Infinite States with with XState Context

[XState] Invoke Child XState Machines from a Parent Machine

[XState] Simplify State Explosion in XState through Hierarchical States