码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-01-19 23:51:24      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:ESS   init   body   event   inter   tin   rms   service   class   

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

标签:ESS   init   body   event   inter   tin   rms   service   class   

原文地址:https://www.cnblogs.com/Answer1215/p/12215853.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!