Class: PlayerActor<TMachine>
API / @xmachines/play-xstate / index / PlayerActor
Defined in: packages/play-xstate/src/player-actor.ts:160
The concrete XState actor. It implements the signal protocol of the Play Architecture
The class extends the Actor class of XState directly, and it implements
@xmachines/play-actor!PlayActor. It gives you the XState v5 integration, and it keeps the
compatibility with the ecosystem, such as the XState inspection and the devtools.
The constructor of the base class receives the machine. Therefore a PlayerActor
is the XState actor, and it is no wrapper around one: every member of the
XState Actor class works on the state of this instance, and this class adds the
reactive state on the TC39 Signals for the observation by the infrastructure.
Capabilities: the class implements both the @xmachines/play-router!index.Routable interface and the @xmachines/play-view!index.Viewable interface. It therefore supports the routing and the view rendering.
Architectural context: the class implements Actor Authority (INV-01),
because the guards of the XState machine control every decision of the
navigation. The infrastructure observes the signals of the actor (state,
currentRoute, and currentView), but it changes no state directly: every
change goes through the event handlers of the state machine.
Examples
The creation of an actor, and its lifecycle
import { setup } from "xstate";import { definePlayer, compose, PlayerActor } from "@xmachines/play-xstate";
const machine = setup({}).createMachine({ initial: "idle", states: { idle: { meta: { route: "/", // A view spec needs `root` and `elements`. Every other shape derives null. view: { root: "home", elements: { home: { type: "HomePage", props: {}, children: [] } }, }, }, }, },});
const createPlayer = definePlayer({ machine });const actor = createPlayer();actor.start();
// Observe the signalsconsole.log(actor.currentRoute.get()); // '/'console.log(actor.currentView.get()?.root); // 'home'The signal lifecycle with a watcher
import { Signal } from "@xmachines/play-signals";
const watcher = new Signal.subtle.Watcher(() => { queueMicrotask(() => { const pending = watcher.getPending(); console.log("State changed:", actor.state.get()); });});
watcher.watch(actor.state);actor.send({ type: "play.route", to: "#about" });// The watcher schedules its own notification in a microtaskSee
- Play RFC
- definePlayer for the creation through a factory
- @xmachines/play-actor!PlayActor for the signal protocol
- @xmachines/play-router!index.Routable for the routing capability
- @xmachines/play-view!index.Viewable for the view rendering capability
Remarks
The routing: this actor supports the route: {} config pattern of XState and
also a play.route event with parameters. The deriveRoute() function reads
meta.route, which is the Stately pattern, for a URL template, and it substitutes
each parameter.
The pattern of the view signal: the currentView signal is a direct
Signal.State, and not a Signal.Computed. The propagation to a watcher in
PlayRenderer is therefore correct. The class derives each view at the entry of a
state and keeps it, and it computes no view on a read.
Extends
Actor<TMachine>
Type Parameters
| Type Parameter | Description |
|---|---|
TMachine extends AnyStateMachine | The type of the XState v5 state machine |
Implements
PlayActor<ReturnType<TMachine["transition"]>,EventFromLogic<TMachine>>
Constructors
Constructor
new PlayerActor<TMachine>( machine, options, input?, restoredSnapshot?): PlayerActor<TMachine>;Defined in: packages/play-xstate/src/player-actor.ts:258
Parameters
| Parameter | Type |
|---|---|
machine | TMachine |
options | PlayerOptions<TMachine> |
input? | InputFrom<TMachine> |
restoredSnapshot? | Snapshot<unknown> |
Returns
PlayerActor<TMachine>
Overrides
Actor<TMachine>.constructorProperties
| Property | Modifier | Type | Description | Inherited from | Defined in |
|---|---|---|---|---|---|
_parent? | public | AnyActorRef | - | Actor._parent | - |
clock | public | Clock | The clock that is responsible for setting and clearing timeouts, such as delayed events and transitions. | Actor.clock | - |
id | public | string | The unique identifier for this actor relative to its parent. | Actor.id | - |
logic | public | TMachine | - | Actor.logic | - |
options | public | Readonly<ActorOptions<TLogic>> | - | Actor.options | - |
ref | public | ActorRef<SnapshotFrom<TMachine>, EventFromLogic<TMachine>, EmittedFrom<TMachine>> | - | Actor.ref | - |
sessionId | public | string | The globally unique process ID for this invocation. | Actor.sessionId | - |
src | public | | string | AnyActorLogic | - | Actor.src | - |
state | public | State<ReturnType<TMachine["transition"]>> | The reactive snapshot of the current actor state. The infrastructure observes this signal, and it reacts to each state change. It therefore holds no coupling to the internal state machine of the actor. | - | packages/play-xstate/src/player-actor.ts:224 |
system | public | AnyActorSystem | The system to which this actor belongs. | Actor.system | - |
systemId | public | string | undefined | - | Actor.systemId | - |
Methods
[dispose]()
dispose: void;Defined in: packages/play-xstate/src/player-actor.ts:611
Stops the actor when the scope of a using declaration ends.
The actor is a Disposable, so a scope that owns one writes no teardown:
{ using actor = definePlayer({ machine })(); actor.start(); actor.send({ type: "go" }); // stop() runs here, and it runs even when send() throws}The release is stop, which is synchronous and idempotent. Disposable and
not AsyncDisposable: a Disposable serves using AND await using, while an
AsyncDisposable raises a TypeError under a plain using.
The key is DISPOSE of @xmachines/play and not a bare Symbol.dispose, so that
the method still answers a using that a bundler downlevelled for a target without
the well-known symbol.
Returns
void
[observable]()
observable: InteropSubscribable<SnapshotFrom<TMachine>>;Defined in: xstate
Returns
InteropSubscribable<SnapshotFrom<TMachine>>
Inherited from
Actor.[observable]can()
can(event): boolean;Defined in: packages/play-xstate/src/player-actor.ts:237
Tells you if the current state of the actor accepts the given event.
The type is the event union of the machine. An unknown event type is therefore a compile error. The method evaluates the event against the snapshot signal.
Parameters
| Parameter | Type |
|---|---|
event | EventFromLogic<TMachine> |
Returns
boolean
Example
if (actor.can({ type: "auth.logout" })) { ... }getPersistedSnapshot()
getPersistedSnapshot(options?): Snapshot<unknown>;Defined in: packages/play-xstate/src/player-actor.ts:562
Returns the persisted snapshot of this actor.
Use it to serialize the state, and to restore it later with the
restore.snapshot option of the factory.
Parameters
| Parameter | Type |
|---|---|
options? | unknown |
Returns
Snapshot<unknown>
Overrides
Actor.getPersistedSnapshot;getSnapshot()
getSnapshot(): SnapshotFrom<TMachine>;Defined in: xstate
Read an actor’s snapshot synchronously.
Returns
SnapshotFrom<TMachine>
Remarks
The snapshot represent an actor’s last emitted value.
When an actor receives an event, its internal state may change. An actor may emit a snapshot when a state transition occurs.
Note that some actors, such as callback actors generated with
fromCallback, will not emit snapshots.
See
- Actor.subscribe to subscribe to an actor’s snapshot values.
- Actor.getPersistedSnapshot to persist the internal state of an actor (which is more than just a snapshot).
Inherited from
Actor.getSnapshot;on()
on<TType>(type, handler): Subscription;Defined in: xstate
Type Parameters
| Type Parameter |
|---|
TType extends any |
Parameters
| Parameter | Type |
|---|---|
type | TType |
handler | (emitted) => void |
Returns
Inherited from
Actor.on;select()
select<TSelected>(selector, equalityFn?): Readable<TSelected>;Defined in: xstate
Type Parameters
| Type Parameter |
|---|
TSelected |
Parameters
| Parameter | Type |
|---|---|
selector | (snapshot) => TSelected |
equalityFn? | (a, b) => boolean |
Returns
Readable<TSelected>
Inherited from
Actor.select;send()
send(event): void;Defined in: packages/play-xstate/src/player-actor.ts:439
Sends an event to this actor.
The guards of the state machine of the actor decide if the event causes a transition. Give any event of the event union of the machine: a domain event, a routing event, and so on.
Parameters
| Parameter | Type | Description |
|---|---|---|
event | EventFromLogic<TMachine> | An event of the EventFromLogic<TMachine> union of the machine. |
Returns
void
Throws
When event is not a plain object, for example
null, undefined, a string, or a number. Import the class from
@xmachines/play-xstate/errors.
Example
// A domain event, with the type of the event union of the machineactor.send({ type: "auth.login", userId: "123" });
// A routing eventactor.send({ type: "play.route", to: "#home" });Implementation of
Overrides
Actor.send;start()
start(): this;Defined in: packages/play-xstate/src/player-actor.ts:365
Starts the actor.
The method fires onStart on each real start, which is every transition from
“not running” to “running”. A start after a stop is such a transition, and XState
permits it: its own start() stops only while the actor RUNS already. A second
call while the actor runs fires no hook. Therefore a defensive double mount runs
the side effects of onStart one time for one real start.
Returns
this
Overrides
Actor.start;stop()
stop(): this;Defined in: packages/play-xstate/src/player-actor.ts:395
Stops the actor and cleans up.
The method fires onStop only when the actor ran. This matches XState, where a
stop of an actor that never started, or of an actor that stopped already, does
nothing and tears nothing down. Therefore the paired cleanup runs never two
times, and it runs never against a resource that onStart did not take. A stop
does not close the actor for ever: a later start() is a new lifecycle, and it
fires onStart again.
Returns
this
Overrides
Actor.stop;subscribe()
Call Signature
subscribe(observer): Subscription;Defined in: packages/play-xstate/src/player-actor.ts:500
Subscribes to the snapshot updates of this actor.
The method accepts an observer object, exactly like Actor.subscribe of XState.
Parameters
| Parameter | Type | Description |
|---|---|---|
observer | Observer<SnapshotFrom<TMachine>> | The observer, with a next, an error, and a complete handler. |
Returns
The subscription, with an unsubscribe() method.
Overrides
Actor.subscribe;Call Signature
subscribe( nextListener?, errorListener?, completeListener?): Subscription;Defined in: packages/play-xstate/src/player-actor.ts:511
Subscribes to the snapshot updates of this actor.
The method accepts listener functions, exactly like Actor.subscribe of XState.
Parameters
| Parameter | Type | Description |
|---|---|---|
nextListener? | (snapshot) => void | The listener function of each snapshot. |
errorListener? | (error) => void | The actor calls it on an error. |
completeListener? | () => void | The actor calls it when it completes, which means that it reaches a final state. |
Returns
The subscription, with an unsubscribe() method.
Overrides
Actor.subscribe;toJSON()
toJSON(): object;Defined in: xstate
Returns
object
| Name | Type | Defined in |
|---|---|---|
id | string | - |
xstate$$type | number | - |
Inherited from
Actor.toJSON;