Emit event from actor spawned with spawnChild #5147
Replies: 2 comments
-
I need to do basically the same thing. I have a fairly complex actor system, three levels of machines. I need to emit events to the software that is instantiating the top-level machine. However, the events that need to be emitted are created in the lowest level machine. Events are emitted from the child actor, but not from the parent. Further, I can't see anyway to 'catch and re-emit' events from within the parent. There are two options that I can see:
|
Beta Was this translation helpful? Give feedback.
-
So, this solution is a little bit hacky, but it might work for you. Create partial wildcard event handler in the top-level actor, like so: on: {
'emit.*': {
actions: [
// console.log for debugging/illustrative purposes...
({ event }) => console.log(`Parent received emit event of type: ${event.type}`),
emit(({ event }) => ({
...event,
type: event.type.replace('emit.', ''),
})),
],
},
}, Then in the child actor, send an XState event to the top-level parent with sendTo(({ context }) => context.parentRef, { type: 'emit.test-event', details: 'foo!' }), This abuses the ability to send XState events to between any actors and the partial wildcard event handling to catch those 'special' events, strip off the marker prefix and re-emit all of the properties from the XState event as an emitted ('JavaScript') event. If you subscribe to events on the parent: // Subscribe to _events_ on the parent
actor.on('*', (event) => {
console.log('Parent emitted:', event);
}); You will see the console output:
|
Beta Was this translation helpful? Give feedback.
-
Hi I am trying to have emitted events come from a child actor created using
spawnChild
The actor looks like this
and my main machine looks like this (simplified)
But I can't seem to get the events when adding a event handler on the statemachine after calling
createActor
on it.Something like
Is there a way to do this or should I be doing something different?
Beta Was this translation helpful? Give feedback.
All reactions