Sending messages directly between actors #4991
-
Is there a way to have actors to send messages to one another directly? I can see how to do it by pushing messages back up to the parent and then having the parent forward them like below, but that seems a bit clunky. Is there a cleaner alternative? const machine = setup({
types: {
events: {} as { type: "MESSAGE_TO_A" } | { type: "MESSAGE_TO_B" },
},
actors: {
a: fromCallback(({ sendBack }) => {
setTimeout(() => {
// Can this be sent directly to b?
sendBack({ type: "MESSAGE_TO_B" })
}, 1000)
}),
b: fromCallback(({ sendBack }) => {
setTimeout(() => {
// Can this be sent directly to a?
sendBack({ type: "MESSAGE_TO_A" })
}, 2000)
}),
},
}).createMachine({
states: {
on: {
MESSAGE_TO_A: {
actions: sendTo("a", { type: "MESSAGE_TO_A" }),
},
MESSAGE_TO_B: {
actions: sendTo("b", { type: "MESSAGE_TO_B" }),
},
},
a: {
invoke: {
id: "a",
src: "a",
},
},
b: {
invoke: {
id: "b",
src: "b",
},
},
},
}) |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 6 replies
-
Yes, add a |
Beta Was this translation helpful? Give feedback.
-
The solution I've settled on so far is this: // ...
a: fromCallback(({system})=>{
setTimeout(() => {
system.scheduler.schedule(
system.get("a"),
system.get("b"),
{ type: "MESSAGE_TO_B" },
0,
undefined
);
}, 1000)
});
// ... This seems to work, but since I couldn't find documentation around it, it makes me think that this might not be the preferred approach... |
Beta Was this translation helpful? Give feedback.
Yeah currently the only official way to handle that is to do what you're doing and send an event to the actor's parent machine and handle sending it on from there.
I like the trick you discovered with
system.schedule
though. Makes me wonder if that couldn't be wrapped up in a cleaner api to make actors created by actor creators a more active part of the system they're in.