首页 > 其他分享 >[XState] Invoke actor

[XState] Invoke actor

时间:2022-11-30 02:22:45浏览次数:41  
标签:const Invoke success actor machine send XState createMachine event

Invoke by Promise:

import { createMachine, interpret, send } from "xstate";

const machine = createMachine({
  initial: "loading",
  states: {
    loading: {
      on: {
        CANCEL: "cancelled",
        NOTIFIY: {
          actions: send("ANY_EVENT", {
            to: "fetchNumber",
          }),
        },
        PING: "success",
      },
      invoke: {
        id: "fetchNumber",
        src: (context, event) => {
         return new Promise((resolve) => {
           setTimeout(() => {
             resolve(12);
           }, 1000);
         });
        },
        src: fetchMachine,
        onDone: {
          target: "success",
          actions: (_, event) => {
            console.log("DONE!", event);
          },
        },
      },
    },
    success: {},
    cancelled: {},
  },
});

const service = interpret(machine).start();

service.subscribe((state) => {
  console.log(state.value);
});

 

 

Invoke by callback:

import { createMachine, interpret, send } from "xstate";

const callback = (sendBack, receive) => {
  let timeout;
  // once receiving event
  // after 1 second,
  // send another PING event back
  receive((event) => {
    console.log("Received", event);
    timeout = setTimeout(() => {
      sendBack({ type: "PING" });
    }, 1000);
  });

  return () => {
    clearTimeout(timeout);
  };
};


const machine = createMachine({
  initial: "loading",
  states: {
    loading: {
      on: {
        CANCEL: "cancelled",
        NOTIFIY: {
          actions: send("ANY_EVENT", {
            to: "fetchNumber",
          }),
        },
        PING: "success",
      },
      invoke: {
        id: "fetchNumber",
        src: (context, event) => callback,
      },
    },
    success: {},
    cancelled: {},
  },
});

const service = interpret(machine).start();

service.subscribe((state) => {
  console.log(state.value);
});

 

Invoke machine:

import { createMachine, interpret, send } from "xstate";

const fetchMachine = createMachine({
  initial: "fetching",
  states: {
    fetching: {
      after: {
        1000: "success",
      },
    },
    success: {
      type: "final",
      data: {
        count: 42,
      },
    },
  },
});

const machine = createMachine({
  initial: "loading",
  states: {
    loading: {
      on: {
        CANCEL: "cancelled",
        NOTIFIY: {
          actions: send("ANY_EVENT", {
            to: "fetchNumber",
          }),
        },
        PING: "success",
      },
      invoke: {
        id: "fetchNumber",
        src: fetchMachine,
      },
    },
    success: {},
    cancelled: {},
  },
});

const service = interpret(machine).start();

service.subscribe((state) => {
  console.log(state.value);
});

 

标签:const,Invoke,success,actor,machine,send,XState,createMachine,event
From: https://www.cnblogs.com/Answer1215/p/16937262.html

相关文章