Actors
When you run a statechart, it becomes an actor, a running process that can receive events. Often, you’ll need your actor to run other actors; spawning new statecharts, waiting for promises, or subscribing to observables.
We use the invoke
attribute on a state to invoke an actor in our machine. You can invoke an actor on any state, including the root node.
ts
import {createMachine } from 'xstate';constmachine =createMachine ({invoke : {src : 'someActor',},},{// `actors` in v5services : {/*** The actor is defined here*/someActor : async () => {},},});
ts
import {createMachine } from 'xstate';constmachine =createMachine ({invoke : {src : 'someActor',},},{// `actors` in v5services : {/*** The actor is defined here*/someActor : async () => {},},});
You can also run several invocations at the same time by specifying invoke
as an array:
ts
import {createMachine } from 'xstate';constmachine =createMachine ({invoke : [{src : 'someActor',},{src : 'someOtherActor',},],},{// `actors` in v5services : {someActor : async () => {},someOtherActor : async () => {},},});
ts
import {createMachine } from 'xstate';constmachine =createMachine ({invoke : [{src : 'someActor',},{src : 'someOtherActor',},],},{// `actors` in v5services : {someActor : async () => {},someOtherActor : async () => {},},});
Running several invocations simultaneously is useful when you want several sub-processes running on the same state.