[XState] Invoke actor

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);
});

 

posted @ 2022-11-30 02:07  Zhentiw  阅读(39)  评论(0编辑  收藏  举报